This is /home/cyd/emacs/doc/lispref/../../info/elisp, produced by
makeinfo version 4.13 from /home/cyd/emacs/doc/lispref/elisp.texi.

This is the `GNU Emacs Lisp Reference Manual' corresponding to Emacs
version 24.2.

Copyright (C) 1990-1996, 1998-2012 Free Software Foundation, Inc.

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.3 or any later version published by the Free Software
     Foundation; with the Invariant Sections being "GNU General Public
     License," with the Front-Cover texts being "A GNU Manual," and
     with the Back-Cover Texts as in (a) below.  A copy of the license
     is included in the section entitled "GNU Free Documentation
     License."

     (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
     modify this GNU manual.  Buying copies from the FSF supports it in
     developing GNU and promoting software freedom."

INFO-DIR-SECTION GNU Emacs Lisp
START-INFO-DIR-ENTRY
* Elisp: (elisp).       The Emacs Lisp Reference Manual.
END-INFO-DIR-ENTRY


File: elisp,  Node: Reading File Names,  Next: Completion Variables,  Prev: High-Level Completion,  Up: Completion

20.6.5 Reading File Names
-------------------------

The high-level completion functions `read-file-name',
`read-directory-name', and `read-shell-command' are designed to read
file names, directory names, and shell commands, respectively.  They
provide special features, including automatic insertion of the default
directory.

 -- Function: read-file-name prompt &optional directory default
          require-match initial predicate
     This function reads a file name, prompting with PROMPT and
     providing completion.

     As an exception, this function reads a file name using a graphical
     file dialog instead of the minibuffer, if all of the following are
     true:

       1. It is invoked via a mouse command.

       2. The selected frame is on a graphical display supporting such
          dialogs.

       3. The variable `use-dialog-box' is non-`nil'.  *Note Dialog
          Boxes: (emacs)Dialog Boxes.

       4. The DIRECTORY argument, described below, does not specify a
          remote file.  *Note Remote Files: (emacs)Remote Files.

     The exact behavior when using a graphical file dialog is
     platform-dependent.  Here, we simply document the behavior when
     using the minibuffer.

     `read-file-name' does not automatically expand the returned file
     name.  You must call `expand-file-name' yourself if an absolute
     file name is required.

     The optional argument REQUIRE-MATCH has the same meaning as in
     `completing-read'.  *Note Minibuffer Completion::.

     The argument DIRECTORY specifies the directory to use for
     completing relative file names.  It should be an absolute directory
     name.  If the variable `insert-default-directory' is non-`nil',
     DIRECTORY is also inserted in the minibuffer as initial input.  It
     defaults to the current buffer's value of `default-directory'.

     If you specify INITIAL, that is an initial file name to insert in
     the buffer (after DIRECTORY, if that is inserted).  In this case,
     point goes at the beginning of INITIAL.  The default for INITIAL
     is `nil'--don't insert any file name.  To see what INITIAL does,
     try the command `C-x C-v' in a buffer visiting a file.  *Please
     note:* we recommend using DEFAULT rather than INITIAL in most
     cases.

     If DEFAULT is non-`nil', then the function returns DEFAULT if the
     user exits the minibuffer with the same non-empty contents that
     `read-file-name' inserted initially.  The initial minibuffer
     contents are always non-empty if `insert-default-directory' is
     non-`nil', as it is by default.  DEFAULT is not checked for
     validity, regardless of the value of REQUIRE-MATCH.  However, if
     REQUIRE-MATCH is non-`nil', the initial minibuffer contents should
     be a valid file (or directory) name.  Otherwise `read-file-name'
     attempts completion if the user exits without any editing, and
     does not return DEFAULT.  DEFAULT is also available through the
     history commands.

     If DEFAULT is `nil', `read-file-name' tries to find a substitute
     default to use in its place, which it treats in exactly the same
     way as if it had been specified explicitly.  If DEFAULT is `nil',
     but INITIAL is non-`nil', then the default is the absolute file
     name obtained from DIRECTORY and INITIAL.  If both DEFAULT and
     INITIAL are `nil' and the buffer is visiting a file,
     `read-file-name' uses the absolute file name of that file as
     default.  If the buffer is not visiting a file, then there is no
     default.  In that case, if the user types <RET> without any
     editing, `read-file-name' simply returns the pre-inserted contents
     of the minibuffer.

     If the user types <RET> in an empty minibuffer, this function
     returns an empty string, regardless of the value of REQUIRE-MATCH.
     This is, for instance, how the user can make the current buffer
     visit no file using `M-x set-visited-file-name'.

     If PREDICATE is non-`nil', it specifies a function of one argument
     that decides which file names are acceptable completion
     alternatives.  A file name is an acceptable value if PREDICATE
     returns non-`nil' for it.

     Here is an example of using `read-file-name':

          (read-file-name "The file is ")

          ;; After evaluation of the preceding expression,
          ;;   the following appears in the minibuffer:

          ---------- Buffer: Minibuffer ----------
          The file is /gp/gnu/elisp/-!-
          ---------- Buffer: Minibuffer ----------

     Typing `manual <TAB>' results in the following:

          ---------- Buffer: Minibuffer ----------
          The file is /gp/gnu/elisp/manual.texi-!-
          ---------- Buffer: Minibuffer ----------

     If the user types <RET>, `read-file-name' returns the file name as
     the string `"/gp/gnu/elisp/manual.texi"'.

 -- Variable: read-file-name-function
     If non-`nil', this should be a function that accepts the same
     arguments as `read-file-name'.  When `read-file-name' is called,
     it calls this function with the supplied arguments instead of
     doing its usual work.

 -- User Option: read-file-name-completion-ignore-case
     If this variable is non-`nil', `read-file-name' ignores case when
     performing completion.

 -- Function: read-directory-name prompt &optional directory default
          require-match initial
     This function is like `read-file-name' but allows only directory
     names as completion alternatives.

     If DEFAULT is `nil' and INITIAL is non-`nil',
     `read-directory-name' constructs a substitute default by combining
     DIRECTORY (or the current buffer's default directory if DIRECTORY
     is `nil') and INITIAL.  If both DEFAULT and INITIAL are `nil',
     this function uses DIRECTORY as substitute default, or the current
     buffer's default directory if DIRECTORY is `nil'.

 -- User Option: insert-default-directory
     This variable is used by `read-file-name', and thus, indirectly,
     by most commands reading file names.  (This includes all commands
     that use the code letters `f' or `F' in their interactive form.
     *Note Code Characters for interactive: Interactive Codes.)  Its
     value controls whether `read-file-name' starts by placing the name
     of the default directory in the minibuffer, plus the initial file
     name, if any.  If the value of this variable is `nil', then
     `read-file-name' does not place any initial input in the
     minibuffer (unless you specify initial input with the INITIAL
     argument).  In that case, the default directory is still used for
     completion of relative file names, but is not displayed.

     If this variable is `nil' and the initial minibuffer contents are
     empty, the user may have to explicitly fetch the next history
     element to access a default value.  If the variable is non-`nil',
     the initial minibuffer contents are always non-empty and the user
     can always request a default value by immediately typing <RET> in
     an unedited minibuffer.  (See above.)

     For example:

          ;; Here the minibuffer starts out with the default directory.
          (let ((insert-default-directory t))
            (read-file-name "The file is "))

          ---------- Buffer: Minibuffer ----------
          The file is ~lewis/manual/-!-
          ---------- Buffer: Minibuffer ----------

          ;; Here the minibuffer is empty and only the prompt
          ;;   appears on its line.
          (let ((insert-default-directory nil))
            (read-file-name "The file is "))

          ---------- Buffer: Minibuffer ----------
          The file is -!-
          ---------- Buffer: Minibuffer ----------

 -- Function: read-shell-command prompt &optional initial history &rest
          args
     This function reads a shell command from the minibuffer, prompting
     with PROMPT and providing intelligent completion.  It completes
     the first word of the command using candidates that are appropriate
     for command names, and the rest of the command words as file names.

     This function uses `minibuffer-local-shell-command-map' as the
     keymap for minibuffer input.  The HISTORY argument specifies the
     history list to use; if is omitted or `nil', it defaults to
     `shell-command-history' (*note shell-command-history: Minibuffer
     History.).  The optional argument INITIAL specifies the initial
     content of the minibuffer (*note Initial Input::).  The rest of
     ARGS, if present, are used as the DEFAULT and INHERIT-INPUT-METHOD
     arguments in `read-from-minibuffer' (*note Text from Minibuffer::).

 -- Variable: minibuffer-local-shell-command-map
     This keymap is used by `read-shell-command' for completing command
     and file names that are part of a shell command.  It uses
     `minibuffer-local-map' as its parent keymap, and binds <TAB> to
     `completion-at-point'.


File: elisp,  Node: Completion Variables,  Next: Programmed Completion,  Prev: Reading File Names,  Up: Completion

20.6.6 Completion Variables
---------------------------

Here are some variables that can be used to alter the default
completion behavior.

 -- User Option: completion-styles
     The value of this variable is a list of completion style (symbols)
     to use for performing completion.  A "completion style" is a set of
     rules for generating completions.  Each symbol occurring this list
     must have a corresponding entry in `completion-styles-alist'.

 -- Variable: completion-styles-alist
     This variable stores a list of available completion styles.  Each
     element in the list has the form

          (STYLE TRY-COMPLETION ALL-COMPLETIONS DOC)

     Here, STYLE is the name of the completion style (a symbol), which
     may be used in the `completion-styles' variable to refer to this
     style; TRY-COMPLETION is the function that does the completion;
     ALL-COMPLETIONS is the function that lists the completions; and
     DOC is a string describing the completion style.

     The TRY-COMPLETION and ALL-COMPLETIONS functions should each
     accept four arguments: STRING, COLLECTION, PREDICATE, and POINT.
     The STRING, COLLECTION, and PREDICATE arguments have the same
     meanings as in `try-completion' (*note Basic Completion::), and
     the POINT argument is the position of point within STRING.  Each
     function should return a non-`nil' value if it performed its job,
     and `nil' if it did not (e.g. if there is no way to complete
     STRING according to the completion style).

     When the user calls a completion command like
     `minibuffer-complete' (*note Completion Commands::), Emacs looks
     for the first style listed in `completion-styles' and calls its
     TRY-COMPLETION function.  If this function returns `nil', Emacs
     moves to the next listed completion style and calls its
     TRY-COMPLETION function, and so on until one of the TRY-COMPLETION
     functions successfully performs completion and returns a non-`nil'
     value.  A similar procedure is used for listing completions, via
     the ALL-COMPLETIONS functions.

     *Note Completion Styles: (emacs)Completion Styles, for a
     description of the available completion styles.

 -- User Option: completion-category-overrides
     This variable specifies special completion styles and other
     completion behaviors to use when completing certain types of text.
     Its value should be an alist with elements of the form `(CATEGORY
     . ALIST)'.  CATEGORY is a symbol describing what is being
     completed; currently, the `buffer', `file', and `unicode-name'
     categories are defined, but others can be defined via specialized
     completion functions (*note Programmed Completion::).  ALIST is an
     association list describing how completion should behave for the
     corresponding category.  The following alist keys are supported:

    `styles'
          The value should be a list of completion styles (symbols).

    `cycle'
          The value should be a value for `completion-cycle-threshold'
          (*note Completion Options: (emacs)Completion Options.) for
          this category.

     Additional alist entries may be defined in the future.

 -- Variable: completion-extra-properties
     This variable is used to specify extra properties of the current
     completion command.  It is intended to be let-bound by specialized
     completion commands.  Its value should be a list of property and
     value pairs.  The following properties are supported:

    `:annotation-function'
          The value should be a function to add annotations in the
          completions buffer.  This function must accept one argument,
          a completion, and should either return `nil' or a string to
          be displayed next to the completion.

    `:exit-function'
          The value should be a function to run after performing
          completion.  The function should accept two arguments, STRING
          and STATUS, where STRING is the text to which the field was
          completed, and STATUS indicates what kind of operation
          happened: `finished' if text is now complete, `sole' if the
          text cannot be further completed but completion is not
          finished, or `exact' if the text is a valid completion but
          may be further completed.


File: elisp,  Node: Programmed Completion,  Next: Completion in Buffers,  Prev: Completion Variables,  Up: Completion

20.6.7 Programmed Completion
----------------------------

Sometimes it is not possible or convenient to create an alist or an
obarray containing all the intended possible completions ahead of time.
In such a case, you can supply your own function to compute the
completion of a given string.  This is called "programmed completion".
Emacs uses programmed completion when completing file names (*note File
Name Completion::), among many other cases.

   To use this feature, pass a function as the COLLECTION argument to
`completing-read'.  The function `completing-read' arranges to pass
your completion function along to `try-completion', `all-completions',
and other basic completion functions, which will then let your function
do all the work.

   The completion function should accept three arguments:

   * The string to be completed.

   * A predicate function with which to filter possible matches, or
     `nil' if none.  The function should call the predicate for each
     possible match, and ignore the match if the predicate returns
     `nil'.

   * A flag specifying the type of completion operation to perform.
     This is one of the following four values:

    `nil'
          This specifies a `try-completion' operation.  The function
          should return `t' if the specified string is a unique and
          exact match; if there is more than one match, it should
          return the common substring of all matches (if the string is
          an exact match for one completion alternative but also
          matches other longer alternatives, the return value is the
          string); if there are no matches, it should return `nil'.

    `t'
          This specifies an `all-completions' operation.  The function
          should return a list of all possible completions of the
          specified string.

    `lambda'
          This specifies a `test-completion' operation.  The function
          should return `t' if the specified string is an exact match
          for some completion alternative; `nil' otherwise.

    `(boundaries . SUFFIX)'
          This specifies a `completion-boundaries' operation.  The
          function should return `(boundaries START . END)', where
          START is the position of the beginning boundary in the
          specified string, and END is the position of the end boundary
          in SUFFIX.

    `metadata'
          This specifies a request for information about the state of
          the current completion.  The function should return an alist,
          as described below.  The alist may contain any number of
          elements.

     If the flag has any other value, the completion function should
     return `nil'.

   The following is a list of metadata entries that a completion
function may return in response to a `metadata' flag argument:

`category'
     The value should be a symbol describing what kind of text the
     completion function is trying to complete.  If the symbol matches
     one of the keys in `completion-category-overrides', the usual
     completion behavior is overridden.  *Note Completion Variables::.

`annotation-function'
     The value should be a function for "annotating" completions.  The
     function should take one argument, STRING, which is a possible
     completion.  It should return a string, which is displayed after
     the completion STRING in the `*Completions*' buffer.

`display-sort-function'
     The value should be a function for sorting completions.  The
     function should take one argument, a list of completion strings,
     and return a sorted list of completion strings.  It is allowed to
     alter the input list destructively.

`cycle-sort-function'
     The value should be a function for sorting completions, when
     `completion-cycle-threshold' is non-`nil' and the user is cycling
     through completion alternatives.  *Note Completion Options:
     (emacs)Completion Options.  Its argument list and return value are
     the same as for `display-sort-function'.

 -- Function: completion-table-dynamic function
     This function is a convenient way to write a function that can act
     as a programmed completion function.  The argument FUNCTION should
     be a function that takes one argument, a string, and returns an
     alist of possible completions of it.  You can think of
     `completion-table-dynamic' as a transducer between that interface
     and the interface for programmed completion functions.


File: elisp,  Node: Completion in Buffers,  Prev: Programmed Completion,  Up: Completion

20.6.8 Completion in Ordinary Buffers
-------------------------------------

Although completion is usually done in the minibuffer, the completion
facility can also be used on the text in ordinary Emacs buffers.  In
many major modes, in-buffer completion is performed by the `C-M-i' or
`M-<TAB>' command, bound to `completion-at-point'.  *Note Symbol
Completion: (emacs)Symbol Completion.  This command uses the abnormal
hook variable `completion-at-point-functions':

 -- Variable: completion-at-point-functions
     The value of this abnormal hook should be a list of functions,
     which are used to compute a completion table for completing the
     text at point.  It can be used by major modes to provide
     mode-specific completion tables (*note Major Mode Conventions::).

     When the command `completion-at-point' runs, it calls the
     functions in the list one by one, without any argument.  Each
     function should return `nil' if it is unable to produce a
     completion table for the text at point.  Otherwise it should
     return a list of the form

          (START END COLLECTION . PROPS)

     START and END delimit the text to complete (which should enclose
     point).  COLLECTION is a completion table for completing that
     text, in a form suitable for passing as the second argument to
     `try-completion' (*note Basic Completion::); completion
     alternatives will be generated from this completion table in the
     usual way, via the completion styles defined in `completion-styles'
     (*note Completion Variables::).  PROPS is a property list for
     additional information; any of the properties in
     `completion-extra-properties' are recognized (*note Completion
     Variables::), as well as the following additional ones:

    `:predicate'
          The value should be a predicate that completion candidates
          need to satisfy.

    `:exclusive'
          If the value is `no', then if the completion table fails to
          match the text at point, `completion-at-point' moves on to the
          next function in `completion-at-point-functions' instead of
          reporting a completion failure.

     A function in `completion-at-point-functions' may also return a
     function.  In that case, that returned function is called, with no
     argument, and it is entirely responsible for performing the
     completion.  We discourage this usage; it is intended to help
     convert old code to using `completion-at-point'.

     The first function in `completion-at-point-functions' to return a
     non-`nil' value is used by `completion-at-point'.  The remaining
     functions are not called.  The exception to this is when there is
     an `:exclusive' specification, as described above.

   The following function provides a convenient way to perform
completion on an arbitrary stretch of text in an Emacs buffer:

 -- Function: completion-in-region start end collection &optional
          predicate
     This function completes the text in the current buffer between the
     positions START and END, using COLLECTION.  The argument
     COLLECTION has the same meaning as in `try-completion' (*note
     Basic Completion::).

     This function inserts the completion text directly into the current
     buffer.  Unlike `completing-read' (*note Minibuffer Completion::),
     it does not activate the minibuffer.

     For this function to work, point must be somewhere between START
     and END.


File: elisp,  Node: Yes-or-No Queries,  Next: Multiple Queries,  Prev: Completion,  Up: Minibuffers

20.7 Yes-or-No Queries
======================

This section describes functions used to ask the user a yes-or-no
question.  The function `y-or-n-p' can be answered with a single
character; it is useful for questions where an inadvertent wrong answer
will not have serious consequences.  `yes-or-no-p' is suitable for more
momentous questions, since it requires three or four characters to
answer.

   If either of these functions is called in a command that was invoked
using the mouse--more precisely, if `last-nonmenu-event' (*note Command
Loop Info::) is either `nil' or a list--then it uses a dialog box or
pop-up menu to ask the question.  Otherwise, it uses keyboard input.
You can force use either of the mouse or of keyboard input by binding
`last-nonmenu-event' to a suitable value around the call.

   Strictly speaking, `yes-or-no-p' uses the minibuffer and `y-or-n-p'
does not; but it seems best to describe them together.

 -- Function: y-or-n-p prompt
     This function asks the user a question, expecting input in the echo
     area.  It returns `t' if the user types `y', `nil' if the user
     types `n'.  This function also accepts <SPC> to mean yes and <DEL>
     to mean no.  It accepts `C-]' to mean "quit", like `C-g', because
     the question might look like a minibuffer and for that reason the
     user might try to use `C-]' to get out.  The answer is a single
     character, with no <RET> needed to terminate it.  Upper and lower
     case are equivalent.

     "Asking the question" means printing PROMPT in the echo area,
     followed by the string `(y or n) '.  If the input is not one of
     the expected answers (`y', `n', `<SPC>', `<DEL>', or something
     that quits), the function responds `Please answer y or n.', and
     repeats the request.

     This function does not actually use the minibuffer, since it does
     not allow editing of the answer.  It actually uses the echo area
     (*note The Echo Area::), which uses the same screen space as the
     minibuffer.  The cursor moves to the echo area while the question
     is being asked.

     The answers and their meanings, even `y' and `n', are not
     hardwired.  The keymap `query-replace-map' specifies them.  *Note
     Search and Replace::.

     In the following example, the user first types `q', which is
     invalid.  At the next prompt the user types `y'.

          (defun ask ()
            (interactive)
            (y-or-n-p "Do you need a lift? "))

          ;; After evaluation of the preceding definition, `M-x ask'
          ;;   causes the following prompt to appear in the echo area:

          ---------- Echo area ----------
          Do you need a lift? (y or n)
          ---------- Echo area ----------

          ;; If the user then types `q', the following appears:

          ---------- Echo area ----------
          Please answer y or n.  Do you need a lift? (y or n)
          ---------- Echo area ----------

          ;; When the user types a valid answer,
          ;;   it is displayed after the question:

          ---------- Echo area ----------
          Do you need a lift? (y or n) y
          ---------- Echo area ----------

     We show successive lines of echo area messages, but only one
     actually appears on the screen at a time.

 -- Function: y-or-n-p-with-timeout prompt seconds default
     Like `y-or-n-p', except that if the user fails to answer within
     SECONDS seconds, this function stops waiting and returns DEFAULT.
     It works by setting up a timer; see *note Timers::.  The argument
     SECONDS may be an integer or a floating point number.

 -- Function: yes-or-no-p prompt
     This function asks the user a question, expecting input in the
     minibuffer.  It returns `t' if the user enters `yes', `nil' if the
     user types `no'.  The user must type <RET> to finalize the
     response.  Upper and lower case are equivalent.

     `yes-or-no-p' starts by displaying PROMPT in the echo area,
     followed by `(yes or no) '.  The user must type one of the
     expected responses; otherwise, the function responds `Please answer
     yes or no.', waits about two seconds and repeats the request.

     `yes-or-no-p' requires more work from the user than `y-or-n-p' and
     is appropriate for more crucial decisions.

     Here is an example:

          (yes-or-no-p "Do you really want to remove everything? ")

          ;; After evaluation of the preceding expression,
          ;;   the following prompt appears,
          ;;   with an empty minibuffer:

          ---------- Buffer: minibuffer ----------
          Do you really want to remove everything? (yes or no)
          ---------- Buffer: minibuffer ----------

     If the user first types `y <RET>', which is invalid because this
     function demands the entire word `yes', it responds by displaying
     these prompts, with a brief pause between them:

          ---------- Buffer: minibuffer ----------
          Please answer yes or no.
          Do you really want to remove everything? (yes or no)
          ---------- Buffer: minibuffer ----------


File: elisp,  Node: Multiple Queries,  Next: Reading a Password,  Prev: Yes-or-No Queries,  Up: Minibuffers

20.8 Asking Multiple Y-or-N Questions
=====================================

When you have a series of similar questions to ask, such as "Do you
want to save this buffer" for each buffer in turn, you should use
`map-y-or-n-p' to ask the collection of questions, rather than asking
each question individually.  This gives the user certain convenient
facilities such as the ability to answer the whole series at once.

 -- Function: map-y-or-n-p prompter actor list &optional help
          action-alist no-cursor-in-echo-area
     This function asks the user a series of questions, reading a
     single-character answer in the echo area for each one.

     The value of LIST specifies the objects to ask questions about.
     It should be either a list of objects or a generator function.  If
     it is a function, it should expect no arguments, and should return
     either the next object to ask about, or `nil', meaning to stop
     asking questions.

     The argument PROMPTER specifies how to ask each question.  If
     PROMPTER is a string, the question text is computed like this:

          (format PROMPTER OBJECT)

     where OBJECT is the next object to ask about (as obtained from
     LIST).

     If not a string, PROMPTER should be a function of one argument
     (the next object to ask about) and should return the question
     text.  If the value is a string, that is the question to ask the
     user.  The function can also return `t', meaning do act on this
     object (and don't ask the user), or `nil', meaning ignore this
     object (and don't ask the user).

     The argument ACTOR says how to act on the answers that the user
     gives.  It should be a function of one argument, and it is called
     with each object that the user says yes for.  Its argument is
     always an object obtained from LIST.

     If the argument HELP is given, it should be a list of this form:

          (SINGULAR PLURAL ACTION)

     where SINGULAR is a string containing a singular noun that
     describes the objects conceptually being acted on, PLURAL is the
     corresponding plural noun, and ACTION is a transitive verb
     describing what ACTOR does.

     If you don't specify HELP, the default is `("object" "objects"
     "act on")'.

     Each time a question is asked, the user may enter `y', `Y', or
     <SPC> to act on that object; `n', `N', or <DEL> to skip that
     object; `!' to act on all following objects; <ESC> or `q' to exit
     (skip all following objects); `.' (period) to act on the current
     object and then exit; or `C-h' to get help.  These are the same
     answers that `query-replace' accepts.  The keymap
     `query-replace-map' defines their meaning for `map-y-or-n-p' as
     well as for `query-replace'; see *note Search and Replace::.

     You can use ACTION-ALIST to specify additional possible answers
     and what they mean.  It is an alist of elements of the form `(CHAR
     FUNCTION HELP)', each of which defines one additional answer.  In
     this element, CHAR is a character (the answer); FUNCTION is a
     function of one argument (an object from LIST); HELP is a string.

     When the user responds with CHAR, `map-y-or-n-p' calls FUNCTION.
     If it returns non-`nil', the object is considered "acted upon",
     and `map-y-or-n-p' advances to the next object in LIST.  If it
     returns `nil', the prompt is repeated for the same object.

     Normally, `map-y-or-n-p' binds `cursor-in-echo-area' while
     prompting.  But if NO-CURSOR-IN-ECHO-AREA is non-`nil', it does
     not do that.

     If `map-y-or-n-p' is called in a command that was invoked using the
     mouse--more precisely, if `last-nonmenu-event' (*note Command Loop
     Info::) is either `nil' or a list--then it uses a dialog box or
     pop-up menu to ask the question.  In this case, it does not use
     keyboard input or the echo area.  You can force use either of the
     mouse or of keyboard input by binding `last-nonmenu-event' to a
     suitable value around the call.

     The return value of `map-y-or-n-p' is the number of objects acted
     on.


File: elisp,  Node: Reading a Password,  Next: Minibuffer Commands,  Prev: Multiple Queries,  Up: Minibuffers

20.9 Reading a Password
=======================

To read a password to pass to another program, you can use the function
`read-passwd'.

 -- Function: read-passwd prompt &optional confirm default
     This function reads a password, prompting with PROMPT.  It does
     not echo the password as the user types it; instead, it echoes `.'
     for each character in the password.

     The optional argument CONFIRM, if non-`nil', says to read the
     password twice and insist it must be the same both times.  If it
     isn't the same, the user has to type it over and over until the
     last two times match.

     The optional argument DEFAULT specifies the default password to
     return if the user enters empty input.  If DEFAULT is `nil', then
     `read-passwd' returns the null string in that case.


File: elisp,  Node: Minibuffer Commands,  Next: Minibuffer Windows,  Prev: Reading a Password,  Up: Minibuffers

20.10 Minibuffer Commands
=========================

This section describes some commands meant for use in the minibuffer.

 -- Command: exit-minibuffer
     This command exits the active minibuffer.  It is normally bound to
     keys in minibuffer local keymaps.

 -- Command: self-insert-and-exit
     This command exits the active minibuffer after inserting the last
     character typed on the keyboard (found in `last-command-event';
     *note Command Loop Info::).

 -- Command: previous-history-element n
     This command replaces the minibuffer contents with the value of the
     Nth previous (older) history element.

 -- Command: next-history-element n
     This command replaces the minibuffer contents with the value of the
     Nth more recent history element.

 -- Command: previous-matching-history-element pattern n
     This command replaces the minibuffer contents with the value of the
     Nth previous (older) history element that matches PATTERN (a
     regular expression).

 -- Command: next-matching-history-element pattern n
     This command replaces the minibuffer contents with the value of the
     Nth next (newer) history element that matches PATTERN (a regular
     expression).

 -- Command: previous-complete-history-element n
     This command replaces the minibuffer contents with the value of the
     Nth previous (older) history element that completes the current
     contents of the minibuffer before the point.

 -- Command: next-complete-history-element n
     This command replaces the minibuffer contents with the value of the
     Nth next (newer) history element that completes the current
     contents of the minibuffer before the point.


File: elisp,  Node: Minibuffer Windows,  Next: Minibuffer Contents,  Prev: Minibuffer Commands,  Up: Minibuffers

20.11 Minibuffer Windows
========================

These functions access and select minibuffer windows and test whether
they are active.

 -- Function: active-minibuffer-window
     This function returns the currently active minibuffer window, or
     `nil' if there is none.

 -- Function: minibuffer-window &optional frame
     This function returns the minibuffer window used for frame FRAME.
     If FRAME is `nil', that stands for the current frame.  Note that
     the minibuffer window used by a frame need not be part of that
     frame--a frame that has no minibuffer of its own necessarily uses
     some other frame's minibuffer window.

 -- Function: set-minibuffer-window window
     This function specifies WINDOW as the minibuffer window to use.
     This affects where the minibuffer is displayed if you put text in
     it without invoking the usual minibuffer commands.  It has no
     effect on the usual minibuffer input functions because they all
     start by choosing the minibuffer window according to the current
     frame.

 -- Function: window-minibuffer-p &optional window
     This function returns non-`nil' if WINDOW is a minibuffer window.
     WINDOW defaults to the selected window.

   It is not correct to determine whether a given window is a
minibuffer by comparing it with the result of `(minibuffer-window)',
because there can be more than one minibuffer window if there is more
than one frame.

 -- Function: minibuffer-window-active-p window
     This function returns non-`nil' if WINDOW is the currently active
     minibuffer window.


File: elisp,  Node: Minibuffer Contents,  Next: Recursive Mini,  Prev: Minibuffer Windows,  Up: Minibuffers

20.12 Minibuffer Contents
=========================

These functions access the minibuffer prompt and contents.

 -- Function: minibuffer-prompt
     This function returns the prompt string of the currently active
     minibuffer.  If no minibuffer is active, it returns `nil'.

 -- Function: minibuffer-prompt-end
     This function returns the current position of the end of the
     minibuffer prompt, if a minibuffer is current.  Otherwise, it
     returns the minimum valid buffer position.

 -- Function: minibuffer-prompt-width
     This function returns the current display-width of the minibuffer
     prompt, if a minibuffer is current.  Otherwise, it returns zero.

 -- Function: minibuffer-contents
     This function returns the editable contents of the minibuffer
     (that is, everything except the prompt) as a string, if a
     minibuffer is current.  Otherwise, it returns the entire contents
     of the current buffer.

 -- Function: minibuffer-contents-no-properties
     This is like `minibuffer-contents', except that it does not copy
     text properties, just the characters themselves.  *Note Text
     Properties::.

 -- Function: minibuffer-completion-contents
     This is like `minibuffer-contents', except that it returns only
     the contents before point.  That is the part that completion
     commands operate on.  *Note Minibuffer Completion::.

 -- Function: delete-minibuffer-contents
     This function erases the editable contents of the minibuffer (that
     is, everything except the prompt), if a minibuffer is current.
     Otherwise, it erases the entire current buffer.


File: elisp,  Node: Recursive Mini,  Next: Minibuffer Misc,  Prev: Minibuffer Contents,  Up: Minibuffers

20.13 Recursive Minibuffers
===========================

These functions and variables deal with recursive minibuffers (*note
Recursive Editing::):

 -- Function: minibuffer-depth
     This function returns the current depth of activations of the
     minibuffer, a nonnegative integer.  If no minibuffers are active,
     it returns zero.

 -- User Option: enable-recursive-minibuffers
     If this variable is non-`nil', you can invoke commands (such as
     `find-file') that use minibuffers even while the minibuffer window
     is active.  Such invocation produces a recursive editing level for
     a new minibuffer.  The outer-level minibuffer is invisible while
     you are editing the inner one.

     If this variable is `nil', you cannot invoke minibuffer commands
     when the minibuffer window is active, not even if you switch to
     another window to do it.

   If a command name has a property `enable-recursive-minibuffers' that
is non-`nil', then the command can use the minibuffer to read arguments
even if it is invoked from the minibuffer.  A command can also achieve
this by binding `enable-recursive-minibuffers' to `t' in the
interactive declaration (*note Using Interactive::).  The minibuffer
command `next-matching-history-element' (normally `M-s' in the
minibuffer) does the latter.


File: elisp,  Node: Minibuffer Misc,  Prev: Recursive Mini,  Up: Minibuffers

20.14 Minibuffer Miscellany
===========================

 -- Function: minibufferp &optional buffer-or-name
     This function returns non-`nil' if BUFFER-OR-NAME is a minibuffer.
     If BUFFER-OR-NAME is omitted, it tests the current buffer.

 -- Variable: minibuffer-setup-hook
     This is a normal hook that is run whenever the minibuffer is
     entered.  *Note Hooks::.

 -- Variable: minibuffer-exit-hook
     This is a normal hook that is run whenever the minibuffer is
     exited.  *Note Hooks::.

 -- Variable: minibuffer-help-form
     The current value of this variable is used to rebind `help-form'
     locally inside the minibuffer (*note Help Functions::).

 -- Variable: minibuffer-scroll-window
     If the value of this variable is non-`nil', it should be a window
     object.  When the function `scroll-other-window' is called in the
     minibuffer, it scrolls this window.

 -- Function: minibuffer-selected-window
     This function returns the window that was selected when the
     minibuffer was entered.  If selected window is not a minibuffer
     window, it returns `nil'.

 -- User Option: max-mini-window-height
     This variable specifies the maximum height for resizing minibuffer
     windows.  If a float, it specifies a fraction of the height of the
     frame.  If an integer, it specifies a number of lines.

 -- Function: minibuffer-message string &rest args
     This function displays STRING temporarily at the end of the
     minibuffer text, for a few seconds, or until the next input event
     arrives, whichever comes first.  The variable
     `minibuffer-message-timeout' specifies the number of seconds to
     wait in the absence of input.  It defaults to 2.  If ARGS is
     non-`nil', the actual message is obtained by passing STRING and
     ARGS through `format'.  *Note Formatting Strings::.

 -- Command: minibuffer-inactive-mode
     This is the major mode used in inactive minibuffers.  It uses
     keymap `minibuffer-inactive-mode-map'.  This can be useful if the
     minibuffer is in a separate frame.  *Note Minibuffers and Frames::.


File: elisp,  Node: Command Loop,  Next: Keymaps,  Prev: Minibuffers,  Up: Top

21 Command Loop
***************

When you run Emacs, it enters the "editor command loop" almost
immediately.  This loop reads key sequences, executes their definitions,
and displays the results.  In this chapter, we describe how these things
are done, and the subroutines that allow Lisp programs to do them.

* Menu:

* Command Overview::    How the command loop reads commands.
* Defining Commands::   Specifying how a function should read arguments.
* Interactive Call::    Calling a command, so that it will read arguments.
* Distinguish Interactive::     Making a command distinguish interactive calls.
* Command Loop Info::   Variables set by the command loop for you to examine.
* Adjusting Point::     Adjustment of point after a command.
* Input Events::        What input looks like when you read it.
* Reading Input::       How to read input events from the keyboard or mouse.
* Special Events::      Events processed immediately and individually.
* Waiting::             Waiting for user input or elapsed time.
* Quitting::            How C-g works.  How to catch or defer quitting.
* Prefix Command Arguments::    How the commands to set prefix args work.
* Recursive Editing::   Entering a recursive edit,
                          and why you usually shouldn't.
* Disabling Commands::  How the command loop handles disabled commands.
* Command History::     How the command history is set up, and how accessed.
* Keyboard Macros::     How keyboard macros are implemented.


File: elisp,  Node: Command Overview,  Next: Defining Commands,  Up: Command Loop

21.1 Command Loop Overview
==========================

The first thing the command loop must do is read a key sequence, which
is a sequence of input events that translates into a command.  It does
this by calling the function `read-key-sequence'.  Lisp programs can
also call this function (*note Key Sequence Input::).  They can also
read input at a lower level with `read-key' or `read-event' (*note
Reading One Event::), or discard pending input with `discard-input'
(*note Event Input Misc::).

   The key sequence is translated into a command through the currently
active keymaps.  *Note Key Lookup::, for information on how this is
done.  The result should be a keyboard macro or an interactively
callable function.  If the key is `M-x', then it reads the name of
another command, which it then calls.  This is done by the command
`execute-extended-command' (*note Interactive Call::).

   Prior to executing the command, Emacs runs `undo-boundary' to create
an undo boundary.  *Note Maintaining Undo::.

   To execute a command, Emacs first reads its arguments by calling
`command-execute' (*note Interactive Call::).  For commands written in
Lisp, the `interactive' specification says how to read the arguments.
This may use the prefix argument (*note Prefix Command Arguments::) or
may read with prompting in the minibuffer (*note Minibuffers::).  For
example, the command `find-file' has an `interactive' specification
which says to read a file name using the minibuffer.  The function body
of `find-file' does not use the minibuffer, so if you call `find-file'
as a function from Lisp code, you must supply the file name string as
an ordinary Lisp function argument.

   If the command is a keyboard macro (i.e. a string or vector), Emacs
executes it using `execute-kbd-macro' (*note Keyboard Macros::).

 -- Variable: pre-command-hook
     This normal hook is run by the editor command loop before it
     executes each command.  At that time, `this-command' contains the
     command that is about to run, and `last-command' describes the
     previous command.  *Note Command Loop Info::.

 -- Variable: post-command-hook
     This normal hook is run by the editor command loop after it
     executes each command (including commands terminated prematurely
     by quitting or by errors).  At that time, `this-command' refers to
     the command that just ran, and `last-command' refers to the
     command before that.

     This hook is also run when Emacs first enters the command loop (at
     which point `this-command' and `last-command' are both `nil').

   Quitting is suppressed while running `pre-command-hook' and
`post-command-hook'.  If an error happens while executing one of these
hooks, it does not terminate execution of the hook; instead the error
is silenced and the function in which the error occurred is removed
from the hook.

   A request coming into the Emacs server (*note Emacs Server:
(emacs)Emacs Server.) runs these two hooks just as a keyboard command
does.


File: elisp,  Node: Defining Commands,  Next: Interactive Call,  Prev: Command Overview,  Up: Command Loop

21.2 Defining Commands
======================

The special form `interactive' turns a Lisp function into a command.
The `interactive' form must be located at top-level in the function
body (usually as the first form in the body), or in the
`interactive-form' property of the function symbol.  When the
`interactive' form is located in the function body, it does nothing
when actually executed.  Its presence serves as a flag, which tells the
Emacs command loop that the function can be called interactively.  The
argument of the `interactive' form controls the reading of arguments
for an interactive call.

* Menu:

* Using Interactive::     General rules for `interactive'.
* Interactive Codes::     The standard letter-codes for reading arguments
                             in various ways.
* Interactive Examples::  Examples of how to read interactive arguments.


File: elisp,  Node: Using Interactive,  Next: Interactive Codes,  Up: Defining Commands

21.2.1 Using `interactive'
--------------------------

This section describes how to write the `interactive' form that makes a
Lisp function an interactively-callable command, and how to examine a
command's `interactive' form.

 -- Special Form: interactive arg-descriptor
     This special form declares that a function is a command, and that
     it may therefore be called interactively (via `M-x' or by entering
     a key sequence bound to it).  The argument ARG-DESCRIPTOR declares
     how to compute the arguments to the command when the command is
     called interactively.

     A command may be called from Lisp programs like any other
     function, but then the caller supplies the arguments and
     ARG-DESCRIPTOR has no effect.

     The `interactive' form must be located at top-level in the
     function body, or in the function symbol's `interactive-form'
     property (*note Symbol Plists::).  It has its effect because the
     command loop looks for it before calling the function (*note
     Interactive Call::).  Once the function is called, all its body
     forms are executed; at this time, if the `interactive' form occurs
     within the body, the form simply returns `nil' without even
     evaluating its argument.

     By convention, you should put the `interactive' form in the
     function body, as the first top-level form.  If there is an
     `interactive' form in both the `interactive-form' symbol property
     and the function body, the former takes precedence.  The
     `interactive-form' symbol property can be used to add an
     interactive form to an existing function, or change how its
     arguments are processed interactively, without redefining the
     function.

   There are three possibilities for the argument ARG-DESCRIPTOR:

   * It may be omitted or `nil'; then the command is called with no
     arguments.  This leads quickly to an error if the command requires
     one or more arguments.

   * It may be a string; its contents are a sequence of elements
     separated by newlines, one for each argument(1).  Each element
     consists of a code character (*note Interactive Codes::)
     optionally followed by a prompt (which some code characters use
     and some ignore).  Here is an example:

          (interactive "P\nbFrobnicate buffer: ")

     The code letter `P' sets the command's first argument to the raw
     command prefix (*note Prefix Command Arguments::).  `bFrobnicate
     buffer: ' prompts the user with `Frobnicate buffer: ' to enter the
     name of an existing buffer, which becomes the second and final
     argument.

     The prompt string can use `%' to include previous argument values
     (starting with the first argument) in the prompt.  This is done
     using `format' (*note Formatting Strings::).  For example, here is
     how you could read the name of an existing buffer followed by a
     new name to give to that buffer:

          (interactive "bBuffer to rename: \nsRename buffer %s to: ")

     If `*' appears at the beginning of the string, then an error is
     signaled if the buffer is read-only.

     If `@' appears at the beginning of the string, and if the key
     sequence used to invoke the command includes any mouse events, then
     the window associated with the first of those events is selected
     before the command is run.

     If `^' appears at the beginning of the string, and if the command
     was invoked through "shift-translation", set the mark and activate
     the region temporarily, or extend an already active region, before
     the command is run.  If the command was invoked without
     shift-translation, and the region is temporarily active,
     deactivate the region before the command is run.
     Shift-translation is controlled on the user level by
     `shift-select-mode'; see *note Shift Selection: (emacs)Shift
     Selection.

     You can use `*', `@', and `^' together; the order does not matter.
     Actual reading of arguments is controlled by the rest of the
     prompt string (starting with the first character that is not `*',
     `@', or `^').

   * It may be a Lisp expression that is not a string; then it should
     be a form that is evaluated to get a list of arguments to pass to
     the command.  Usually this form will call various functions to
     read input from the user, most often through the minibuffer (*note
     Minibuffers::) or directly from the keyboard (*note Reading
     Input::).

     Providing point or the mark as an argument value is also common,
     but if you do this _and_ read input (whether using the minibuffer
     or not), be sure to get the integer values of point or the mark
     after reading.  The current buffer may be receiving subprocess
     output; if subprocess output arrives while the command is waiting
     for input, it could relocate point and the mark.

     Here's an example of what _not_ to do:

          (interactive
           (list (region-beginning) (region-end)
                 (read-string "Foo: " nil 'my-history)))

     Here's how to avoid the problem, by examining point and the mark
     after reading the keyboard input:

          (interactive
           (let ((string (read-string "Foo: " nil 'my-history)))
             (list (region-beginning) (region-end) string)))

     *Warning:* the argument values should not include any data types
     that can't be printed and then read.  Some facilities save
     `command-history' in a file to be read in the subsequent sessions;
     if a command's arguments contain a data type that prints using
     `#<...>' syntax, those facilities won't work.

     There are, however, a few exceptions: it is ok to use a limited
     set of expressions such as `(point)', `(mark)',
     `(region-beginning)', and `(region-end)', because Emacs recognizes
     them specially and puts the expression (rather than its value)
     into the command history.  To see whether the expression you wrote
     is one of these exceptions, run the command, then examine `(car
     command-history)'.

 -- Function: interactive-form function
     This function returns the `interactive' form of FUNCTION.  If
     FUNCTION is an interactively callable function (*note Interactive
     Call::), the value is the command's `interactive' form
     `(interactive SPEC)', which specifies how to compute its
     arguments.  Otherwise, the value is `nil'.  If FUNCTION is a
     symbol, its function definition is used.

   ---------- Footnotes ----------

   (1) Some elements actually supply two arguments.


File: elisp,  Node: Interactive Codes,  Next: Interactive Examples,  Prev: Using Interactive,  Up: Defining Commands

21.2.2 Code Characters for `interactive'
----------------------------------------

The code character descriptions below contain a number of key words,
defined here as follows:

Completion
     Provide completion.  <TAB>, <SPC>, and <RET> perform name
     completion because the argument is read using `completing-read'
     (*note Completion::).  `?' displays a list of possible completions.

Existing
     Require the name of an existing object.  An invalid name is not
     accepted; the commands to exit the minibuffer do not exit if the
     current input is not valid.

Default
     A default value of some sort is used if the user enters no text in
     the minibuffer.  The default depends on the code character.

No I/O
     This code letter computes an argument without reading any input.
     Therefore, it does not use a prompt string, and any prompt string
     you supply is ignored.

     Even though the code letter doesn't use a prompt string, you must
     follow it with a newline if it is not the last code character in
     the string.

Prompt
     A prompt immediately follows the code character.  The prompt ends
     either with the end of the string or with a newline.

Special
     This code character is meaningful only at the beginning of the
     interactive string, and it does not look for a prompt or a newline.
     It is a single, isolated character.

   Here are the code character descriptions for use with `interactive':

`*'
     Signal an error if the current buffer is read-only.  Special.

`@'
     Select the window mentioned in the first mouse event in the key
     sequence that invoked this command.  Special.

`^'
     If the command was invoked through shift-translation, set the mark
     and activate the region temporarily, or extend an already active
     region, before the command is run.  If the command was invoked
     without shift-translation, and the region is temporarily active,
     deactivate the region before the command is run.  Special.

`a'
     A function name (i.e., a symbol satisfying `fboundp').  Existing,
     Completion, Prompt.

`b'
     The name of an existing buffer.  By default, uses the name of the
     current buffer (*note Buffers::).  Existing, Completion, Default,
     Prompt.

`B'
     A buffer name.  The buffer need not exist.  By default, uses the
     name of a recently used buffer other than the current buffer.
     Completion, Default, Prompt.

`c'
     A character.  The cursor does not move into the echo area.  Prompt.

`C'
     A command name (i.e., a symbol satisfying `commandp').  Existing,
     Completion, Prompt.

`d'
     The position of point, as an integer (*note Point::).  No I/O.

`D'
     A directory name.  The default is the current default directory of
     the current buffer, `default-directory' (*note File Name
     Expansion::).  Existing, Completion, Default, Prompt.

`e'
     The first or next mouse event in the key sequence that invoked the
     command.  More precisely, `e' gets events that are lists, so you
     can look at the data in the lists.  *Note Input Events::.  No I/O.

     You can use `e' more than once in a single command's interactive
     specification.  If the key sequence that invoked the command has N
     events that are lists, the Nth `e' provides the Nth such event.
     Events that are not lists, such as function keys and ASCII
     characters, do not count where `e' is concerned.

`f'
     A file name of an existing file (*note File Names::).  The default
     directory is `default-directory'.  Existing, Completion, Default,
     Prompt.

`F'
     A file name.  The file need not exist.  Completion, Default,
     Prompt.

`G'
     A file name.  The file need not exist.  If the user enters just a
     directory name, then the value is just that directory name, with no
     file name within the directory added.  Completion, Default, Prompt.

`i'
     An irrelevant argument.  This code always supplies `nil' as the
     argument's value.  No I/O.

`k'
     A key sequence (*note Key Sequences::).  This keeps reading events
     until a command (or undefined command) is found in the current key
     maps.  The key sequence argument is represented as a string or
     vector.  The cursor does not move into the echo area.  Prompt.

     If `k' reads a key sequence that ends with a down-event, it also
     reads and discards the following up-event.  You can get access to
     that up-event with the `U' code character.

     This kind of input is used by commands such as `describe-key' and
     `global-set-key'.

`K'
     A key sequence, whose definition you intend to change.  This works
     like `k', except that it suppresses, for the last input event in
     the key sequence, the conversions that are normally used (when
     necessary) to convert an undefined key into a defined one.

`m'
     The position of the mark, as an integer.  No I/O.

`M'
     Arbitrary text, read in the minibuffer using the current buffer's
     input method, and returned as a string (*note Input Methods:
     (emacs)Input Methods.).  Prompt.

`n'
     A number, read with the minibuffer.  If the input is not a number,
     the user has to try again.  `n' never uses the prefix argument.
     Prompt.

`N'
     The numeric prefix argument; but if there is no prefix argument,
     read a number as with `n'.  The value is always a number.  *Note
     Prefix Command Arguments::.  Prompt.

`p'
     The numeric prefix argument.  (Note that this `p' is lower case.)
     No I/O.

`P'
     The raw prefix argument.  (Note that this `P' is upper case.)  No
     I/O.

`r'
     Point and the mark, as two numeric arguments, smallest first.
     This is the only code letter that specifies two successive
     arguments rather than one.  No I/O.

`s'
     Arbitrary text, read in the minibuffer and returned as a string
     (*note Text from Minibuffer::).  Terminate the input with either
     `C-j' or <RET>.  (`C-q' may be used to include either of these
     characters in the input.)  Prompt.

`S'
     An interned symbol whose name is read in the minibuffer.  Any
     whitespace character terminates the input.  (Use `C-q' to include
     whitespace in the string.)  Other characters that normally
     terminate a symbol (e.g., parentheses and brackets) do not do so
     here.  Prompt.

`U'
     A key sequence or `nil'.  Can be used after a `k' or `K' argument
     to get the up-event that was discarded (if any) after `k' or `K'
     read a down-event.  If no up-event has been discarded, `U'
     provides `nil' as the argument.  No I/O.

`v'
     A variable declared to be a user option (i.e., satisfying the
     predicate `user-variable-p').  This reads the variable using
     `read-variable'.  *Note Definition of read-variable::.  Existing,
     Completion, Prompt.

`x'
     A Lisp object, specified with its read syntax, terminated with a
     `C-j' or <RET>.  The object is not evaluated.  *Note Object from
     Minibuffer::.  Prompt.

`X'
     A Lisp form's value.  `X' reads as `x' does, then evaluates the
     form so that its value becomes the argument for the command.
     Prompt.

`z'
     A coding system name (a symbol).  If the user enters null input,
     the argument value is `nil'.  *Note Coding Systems::.  Completion,
     Existing, Prompt.

`Z'
     A coding system name (a symbol)--but only if this command has a
     prefix argument.  With no prefix argument, `Z' provides `nil' as
     the argument value.  Completion, Existing, Prompt.


File: elisp,  Node: Interactive Examples,  Prev: Interactive Codes,  Up: Defining Commands

21.2.3 Examples of Using `interactive'
--------------------------------------

Here are some examples of `interactive':

     (defun foo1 ()              ; `foo1' takes no arguments,
         (interactive)           ;   just moves forward two words.
         (forward-word 2))
          => foo1

     (defun foo2 (n)             ; `foo2' takes one argument,
         (interactive "^p")      ;   which is the numeric prefix.
                                 ; under `shift-select-mode',
                                 ;   will activate or extend region.
         (forward-word (* 2 n)))
          => foo2

     (defun foo3 (n)             ; `foo3' takes one argument,
         (interactive "nCount:") ;   which is read with the Minibuffer.
         (forward-word (* 2 n)))
          => foo3

     (defun three-b (b1 b2 b3)
       "Select three existing buffers.
     Put them into three windows, selecting the last one."
         (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
         (delete-other-windows)
         (split-window (selected-window) 8)
         (switch-to-buffer b1)
         (other-window 1)
         (split-window (selected-window) 8)
         (switch-to-buffer b2)
         (other-window 1)
         (switch-to-buffer b3))
          => three-b
     (three-b "*scratch*" "declarations.texi" "*mail*")
          => nil


File: elisp,  Node: Interactive Call,  Next: Distinguish Interactive,  Prev: Defining Commands,  Up: Command Loop

21.3 Interactive Call
=====================

After the command loop has translated a key sequence into a command, it
invokes that command using the function `command-execute'.  If the
command is a function, `command-execute' calls `call-interactively',
which reads the arguments and calls the command.  You can also call
these functions yourself.

   Note that the term "command", in this context, refers to an
interactively callable function (or function-like object), or a
keyboard macro.  It does not refer to the key sequence used to invoke a
command (*note Keymaps::).

 -- Function: commandp object &optional for-call-interactively
     This function returns `t' if OBJECT is a command.  Otherwise, it
     returns `nil'.

     Commands include strings and vectors (which are treated as keyboard
     macros), lambda expressions that contain a top-level `interactive'
     form (*note Using Interactive::), byte-code function objects made
     from such lambda expressions, autoload objects that are declared
     as interactive (non-`nil' fourth argument to `autoload'), and some
     primitive functions.  Also, a symbol is considered a command if it
     has a non-`nil' `interactive-form' property, or if its function
     definition satisfies `commandp'.

     If FOR-CALL-INTERACTIVELY is non-`nil', then `commandp' returns
     `t' only for objects that `call-interactively' could call--thus,
     not for keyboard macros.

     See `documentation' in *note Accessing Documentation::, for a
     realistic example of using `commandp'.

 -- Function: call-interactively command &optional record-flag keys
     This function calls the interactively callable function COMMAND,
     providing arguments according to its interactive calling
     specifications.  It returns whatever COMMAND returns.

     If, for instance, you have a function with the following signature:

          (defun foo (begin end)
            (interactive "r")
            ...)

     then saying

          (call-interactively 'foo)

     will call `foo' with the region (`point' and `mark') as the
     arguments.

     An error is signaled if COMMAND is not a function or if it cannot
     be called interactively (i.e., is not a command).  Note that
     keyboard macros (strings and vectors) are not accepted, even though
     they are considered commands, because they are not functions.  If
     COMMAND is a symbol, then `call-interactively' uses its function
     definition.

     If RECORD-FLAG is non-`nil', then this command and its arguments
     are unconditionally added to the list `command-history'.
     Otherwise, the command is added only if it uses the minibuffer to
     read an argument.  *Note Command History::.

     The argument KEYS, if given, should be a vector which specifies
     the sequence of events to supply if the command inquires which
     events were used to invoke it.  If KEYS is omitted or `nil', the
     default is the return value of `this-command-keys-vector'.  *Note
     Definition of this-command-keys-vector::.

 -- Function: command-execute command &optional record-flag keys special
     This function executes COMMAND.  The argument COMMAND must satisfy
     the `commandp' predicate; i.e., it must be an interactively
     callable function or a keyboard macro.

     A string or vector as COMMAND is executed with
     `execute-kbd-macro'.  A function is passed to `call-interactively'
     (see above), along with the RECORD-FLAG and KEYS arguments.

     If COMMAND is a symbol, its function definition is used in its
     place.  A symbol with an `autoload' definition counts as a command
     if it was declared to stand for an interactively callable
     function.  Such a definition is handled by loading the specified
     library and then rechecking the definition of the symbol.

     The argument SPECIAL, if given, means to ignore the prefix
     argument and not clear it.  This is used for executing special
     events (*note Special Events::).

 -- Command: execute-extended-command prefix-argument
     This function reads a command name from the minibuffer using
     `completing-read' (*note Completion::).  Then it uses
     `command-execute' to call the specified command.  Whatever that
     command returns becomes the value of `execute-extended-command'.

     If the command asks for a prefix argument, it receives the value
     PREFIX-ARGUMENT.  If `execute-extended-command' is called
     interactively, the current raw prefix argument is used for
     PREFIX-ARGUMENT, and thus passed on to whatever command is run.

     `execute-extended-command' is the normal definition of `M-x', so
     it uses the string `M-x ' as a prompt.  (It would be better to
     take the prompt from the events used to invoke
     `execute-extended-command', but that is painful to implement.)  A
     description of the value of the prefix argument, if any, also
     becomes part of the prompt.

          (execute-extended-command 3)
          ---------- Buffer: Minibuffer ----------
          3 M-x forward-word RET
          ---------- Buffer: Minibuffer ----------
               => t


File: elisp,  Node: Distinguish Interactive,  Next: Command Loop Info,  Prev: Interactive Call,  Up: Command Loop

21.4 Distinguish Interactive Calls
==================================

Sometimes a command should display additional visual feedback (such as
an informative message in the echo area) for interactive calls only.
There are three ways to do this.  The recommended way to test whether
the function was called using `call-interactively' is to give it an
optional argument `print-message' and use the `interactive' spec to
make it non-`nil' in interactive calls.  Here's an example:

     (defun foo (&optional print-message)
       (interactive "p")
       (when print-message
         (message "foo")))

We use `"p"' because the numeric prefix argument is never `nil'.
Defined in this way, the function does display the message when called
from a keyboard macro.

   The above method with the additional argument is usually best,
because it allows callers to say "treat this call as interactive".  But
you can also do the job by testing `called-interactively-p'.

 -- Function: called-interactively-p kind
     This function returns `t' when the calling function was called
     using `call-interactively'.

     The argument KIND should be either the symbol `interactive' or the
     symbol `any'.  If it is `interactive', then
     `called-interactively-p' returns `t' only if the call was made
     directly by the user--e.g., if the user typed a key sequence bound
     to the calling function, but _not_ if the user ran a keyboard
     macro that called the function (*note Keyboard Macros::).  If KIND
     is `any', `called-interactively-p' returns `t' for any kind of
     interactive call, including keyboard macros.

     If in doubt, use `any'; the only known proper use of `interactive'
     is if you need to decide whether to display a helpful message
     while a function is running.

     A function is never considered to be called interactively if it was
     called via Lisp evaluation (or with `apply' or `funcall').

Here is an example of using `called-interactively-p':

     (defun foo ()
       (interactive)
       (when (called-interactively-p 'any)
         (message "Interactive!")
         'foo-called-interactively))

     ;; Type `M-x foo'.
          -| Interactive!

     (foo)
          => nil

Here is another example that contrasts direct and indirect calls to
`called-interactively-p'.

     (defun bar ()
       (interactive)
       (message "%s" (list (foo) (called-interactively-p 'any))))

     ;; Type `M-x bar'.
          -| (nil t)


File: elisp,  Node: Command Loop Info,  Next: Adjusting Point,  Prev: Distinguish Interactive,  Up: Command Loop

21.5 Information from the Command Loop
======================================

The editor command loop sets several Lisp variables to keep status
records for itself and for commands that are run.  With the exception of
`this-command' and `last-command' it's generally a bad idea to change
any of these variables in a Lisp program.

 -- Variable: last-command
     This variable records the name of the previous command executed by
     the command loop (the one before the current command).  Normally
     the value is a symbol with a function definition, but this is not
     guaranteed.

     The value is copied from `this-command' when a command returns to
     the command loop, except when the command has specified a prefix
     argument for the following command.

     This variable is always local to the current terminal and cannot be
     buffer-local.  *Note Multiple Terminals::.

 -- Variable: real-last-command
     This variable is set up by Emacs just like `last-command', but
     never altered by Lisp programs.

 -- Variable: last-repeatable-command
     This variable stores the most recently executed command that was
     not part of an input event.  This is the command `repeat' will try
     to repeat, *Note Repeating: (emacs)Repeating.

 -- Variable: this-command
     This variable records the name of the command now being executed by
     the editor command loop.  Like `last-command', it is normally a
     symbol with a function definition.

     The command loop sets this variable just before running a command,
     and copies its value into `last-command' when the command finishes
     (unless the command specified a prefix argument for the following
     command).

     Some commands set this variable during their execution, as a flag
     for whatever command runs next.  In particular, the functions for
     killing text set `this-command' to `kill-region' so that any kill
     commands immediately following will know to append the killed text
     to the previous kill.

   If you do not want a particular command to be recognized as the
previous command in the case where it got an error, you must code that
command to prevent this.  One way is to set `this-command' to `t' at the
beginning of the command, and set `this-command' back to its proper
value at the end, like this:

     (defun foo (args...)
       (interactive ...)
       (let ((old-this-command this-command))
         (setq this-command t)
         ...do the work...
         (setq this-command old-this-command)))

We do not bind `this-command' with `let' because that would restore the
old value in case of error--a feature of `let' which in this case does
precisely what we want to avoid.

 -- Variable: this-original-command
     This has the same value as `this-command' except when command
     remapping occurs (*note Remapping Commands::).  In that case,
     `this-command' gives the command actually run (the result of
     remapping), and `this-original-command' gives the command that was
     specified to run but remapped into another command.

 -- Function: this-command-keys
     This function returns a string or vector containing the key
     sequence that invoked the present command, plus any previous
     commands that generated the prefix argument for this command.  Any
     events read by the command using `read-event' without a timeout
     get tacked on to the end.

     However, if the command has called `read-key-sequence', it returns
     the last read key sequence.  *Note Key Sequence Input::.  The
     value is a string if all events in the sequence were characters
     that fit in a string.  *Note Input Events::.

          (this-command-keys)
          ;; Now use `C-u C-x C-e' to evaluate that.
               => "^U^X^E"

 -- Function: this-command-keys-vector
     Like `this-command-keys', except that it always returns the events
     in a vector, so you don't need to deal with the complexities of
     storing input events in a string (*note Strings of Events::).

 -- Function: clear-this-command-keys &optional keep-record
     This function empties out the table of events for
     `this-command-keys' to return.  Unless KEEP-RECORD is non-`nil',
     it also empties the records that the function `recent-keys' (*note
     Recording Input::) will subsequently return.  This is useful after
     reading a password, to prevent the password from echoing
     inadvertently as part of the next command in certain cases.

 -- Variable: last-nonmenu-event
     This variable holds the last input event read as part of a key
     sequence, not counting events resulting from mouse menus.

     One use of this variable is for telling `x-popup-menu' where to pop
     up a menu.  It is also used internally by `y-or-n-p' (*note
     Yes-or-No Queries::).

 -- Variable: last-command-event
 -- Variable: last-command-char
     This variable is set to the last input event that was read by the
     command loop as part of a command.  The principal use of this
     variable is in `self-insert-command', which uses it to decide which
     character to insert.

          last-command-event
          ;; Now use `C-u C-x C-e' to evaluate that.
               => 5

     The value is 5 because that is the ASCII code for `C-e'.

     The alias `last-command-char' is obsolete.

 -- Variable: last-event-frame
     This variable records which frame the last input event was
     directed to.  Usually this is the frame that was selected when the
     event was generated, but if that frame has redirected input focus
     to another frame, the value is the frame to which the event was
     redirected.  *Note Input Focus::.

     If the last event came from a keyboard macro, the value is `macro'.


File: elisp,  Node: Adjusting Point,  Next: Input Events,  Prev: Command Loop Info,  Up: Command Loop

21.6 Adjusting Point After Commands
===================================

It is not easy to display a value of point in the middle of a sequence
of text that has the `display', `composition' or is invisible.
Therefore, after a command finishes and returns to the command loop, if
point is within such a sequence, the command loop normally moves point
to the edge of the sequence.

   A command can inhibit this feature by setting the variable
`disable-point-adjustment':

 -- Variable: disable-point-adjustment
     If this variable is non-`nil' when a command returns to the
     command loop, then the command loop does not check for those text
     properties, and does not move point out of sequences that have
     them.

     The command loop sets this variable to `nil' before each command,
     so if a command sets it, the effect applies only to that command.

 -- Variable: global-disable-point-adjustment
     If you set this variable to a non-`nil' value, the feature of
     moving point out of these sequences is completely turned off.


File: elisp,  Node: Input Events,  Next: Reading Input,  Prev: Adjusting Point,  Up: Command Loop

21.7 Input Events
=================

The Emacs command loop reads a sequence of "input events" that
represent keyboard or mouse activity.  The events for keyboard activity
are characters or symbols; mouse events are always lists.  This section
describes the representation and meaning of input events in detail.

 -- Function: eventp object
     This function returns non-`nil' if OBJECT is an input event or
     event type.

     Note that any symbol might be used as an event or an event type.
     `eventp' cannot distinguish whether a symbol is intended by Lisp
     code to be used as an event.  Instead, it distinguishes whether the
     symbol has actually been used in an event that has been read as
     input in the current Emacs session.  If a symbol has not yet been
     so used, `eventp' returns `nil'.

* Menu:

* Keyboard Events::             Ordinary characters--keys with symbols on them.
* Function Keys::               Function keys--keys with names, not symbols.
* Mouse Events::                Overview of mouse events.
* Click Events::                Pushing and releasing a mouse button.
* Drag Events::                 Moving the mouse before releasing the button.
* Button-Down Events::          A button was pushed and not yet released.
* Repeat Events::               Double and triple click (or drag, or down).
* Motion Events::               Just moving the mouse, not pushing a button.
* Focus Events::                Moving the mouse between frames.
* Misc Events::                 Other events the system can generate.
* Event Examples::              Examples of the lists for mouse events.
* Classifying Events::          Finding the modifier keys in an event symbol.
                                Event types.
* Accessing Mouse::             Functions to extract info from mouse events.
* Accessing Scroll::            Functions to get info from scroll bar events.
* Strings of Events::           Special considerations for putting
                                  keyboard character events in a string.


File: elisp,  Node: Keyboard Events,  Next: Function Keys,  Up: Input Events

21.7.1 Keyboard Events
----------------------

There are two kinds of input you can get from the keyboard: ordinary
keys, and function keys.  Ordinary keys correspond to characters; the
events they generate are represented in Lisp as characters.  The event
type of a character event is the character itself (an integer); see
*note Classifying Events::.

   An input character event consists of a "basic code" between 0 and
524287, plus any or all of these "modifier bits":

meta
     The 2**27 bit in the character code indicates a character typed
     with the meta key held down.

control
     The 2**26 bit in the character code indicates a non-ASCII control
     character.

     ASCII control characters such as `C-a' have special basic codes of
     their own, so Emacs needs no special bit to indicate them.  Thus,
     the code for `C-a' is just 1.

     But if you type a control combination not in ASCII, such as `%'
     with the control key, the numeric value you get is the code for
     `%' plus 2**26 (assuming the terminal supports non-ASCII control
     characters).

shift
     The 2**25 bit in the character code indicates an ASCII control
     character typed with the shift key held down.

     For letters, the basic code itself indicates upper versus lower
     case; for digits and punctuation, the shift key selects an
     entirely different character with a different basic code.  In
     order to keep within the ASCII character set whenever possible,
     Emacs avoids using the 2**25 bit for those characters.

     However, ASCII provides no way to distinguish `C-A' from `C-a', so
     Emacs uses the 2**25 bit in `C-A' and not in `C-a'.

hyper
     The 2**24 bit in the character code indicates a character typed
     with the hyper key held down.

super
     The 2**23 bit in the character code indicates a character typed
     with the super key held down.

alt
     The 2**22 bit in the character code indicates a character typed
     with the alt key held down.  (The key labeled <Alt> on most
     keyboards is actually treated as the meta key, not this.)

   It is best to avoid mentioning specific bit numbers in your program.
To test the modifier bits of a character, use the function
`event-modifiers' (*note Classifying Events::).  When making key
bindings, you can use the read syntax for characters with modifier bits
(`\C-', `\M-', and so on).  For making key bindings with `define-key',
you can use lists such as `(control hyper ?x)' to specify the
characters (*note Changing Key Bindings::).  The function
`event-convert-list' converts such a list into an event type (*note
Classifying Events::).


File: elisp,  Node: Function Keys,  Next: Mouse Events,  Prev: Keyboard Events,  Up: Input Events

21.7.2 Function Keys
--------------------

Most keyboards also have "function keys"--keys that have names or
symbols that are not characters.  Function keys are represented in
Emacs Lisp as symbols; the symbol's name is the function key's label,
in lower case.  For example, pressing a key labeled <F1> generates an
input event represented by the symbol `f1'.

   The event type of a function key event is the event symbol itself.
*Note Classifying Events::.

   Here are a few special cases in the symbol-naming convention for
function keys:

`backspace', `tab', `newline', `return', `delete'
     These keys correspond to common ASCII control characters that have
     special keys on most keyboards.

     In ASCII, `C-i' and <TAB> are the same character.  If the terminal
     can distinguish between them, Emacs conveys the distinction to
     Lisp programs by representing the former as the integer 9, and the
     latter as the symbol `tab'.

     Most of the time, it's not useful to distinguish the two.  So
     normally `local-function-key-map' (*note Translation Keymaps::) is
     set up to map `tab' into 9.  Thus, a key binding for character
     code 9 (the character `C-i') also applies to `tab'.  Likewise for
     the other symbols in this group.  The function `read-char'
     likewise converts these events into characters.

     In ASCII, <BS> is really `C-h'.  But `backspace' converts into the
     character code 127 (<DEL>), not into code 8 (<BS>).  This is what
     most users prefer.

`left', `up', `right', `down'
     Cursor arrow keys

`kp-add', `kp-decimal', `kp-divide', ...
     Keypad keys (to the right of the regular keyboard).

`kp-0', `kp-1', ...
     Keypad keys with digits.

`kp-f1', `kp-f2', `kp-f3', `kp-f4'
     Keypad PF keys.

`kp-home', `kp-left', `kp-up', `kp-right', `kp-down'
     Keypad arrow keys.  Emacs normally translates these into the
     corresponding non-keypad keys `home', `left', ...

`kp-prior', `kp-next', `kp-end', `kp-begin', `kp-insert', `kp-delete'
     Additional keypad duplicates of keys ordinarily found elsewhere.
     Emacs normally translates these into the like-named non-keypad
     keys.

   You can use the modifier keys <ALT>, <CTRL>, <HYPER>, <META>,
<SHIFT>, and <SUPER> with function keys.  The way to represent them is
with prefixes in the symbol name:

`A-'
     The alt modifier.

`C-'
     The control modifier.

`H-'
     The hyper modifier.

`M-'
     The meta modifier.

`S-'
     The shift modifier.

`s-'
     The super modifier.

   Thus, the symbol for the key <F3> with <META> held down is `M-f3'.
When you use more than one prefix, we recommend you write them in
alphabetical order; but the order does not matter in arguments to the
key-binding lookup and modification functions.


File: elisp,  Node: Mouse Events,  Next: Click Events,  Prev: Function Keys,  Up: Input Events

21.7.3 Mouse Events
-------------------

Emacs supports four kinds of mouse events: click events, drag events,
button-down events, and motion events.  All mouse events are represented
as lists.  The CAR of the list is the event type; this says which mouse
button was involved, and which modifier keys were used with it.  The
event type can also distinguish double or triple button presses (*note
Repeat Events::).  The rest of the list elements give position and time
information.

   For key lookup, only the event type matters: two events of the same
type necessarily run the same command.  The command can access the full
values of these events using the `e' interactive code.  *Note
Interactive Codes::.

   A key sequence that starts with a mouse event is read using the
keymaps of the buffer in the window that the mouse was in, not the
current buffer.  This does not imply that clicking in a window selects
that window or its buffer--that is entirely under the control of the
command binding of the key sequence.


File: elisp,  Node: Click Events,  Next: Drag Events,  Prev: Mouse Events,  Up: Input Events

21.7.4 Click Events
-------------------

When the user presses a mouse button and releases it at the same
location, that generates a "click" event.  All mouse click event share
the same format:

     (EVENT-TYPE POSITION CLICK-COUNT)

EVENT-TYPE
     This is a symbol that indicates which mouse button was used.  It is
     one of the symbols `mouse-1', `mouse-2', ..., where the buttons
     are numbered left to right.

     You can also use prefixes `A-', `C-', `H-', `M-', `S-' and `s-'
     for modifiers alt, control, hyper, meta, shift and super, just as
     you would with function keys.

     This symbol also serves as the event type of the event.  Key
     bindings describe events by their types; thus, if there is a key
     binding for `mouse-1', that binding would apply to all events whose
     EVENT-TYPE is `mouse-1'.

POSITION
     This is the position where the mouse click occurred.  The actual
     format of POSITION depends on what part of a window was clicked on.

     For mouse click events in the text area, mode line, header line,
     or in the marginal areas, POSITION has this form:

          (WINDOW POS-OR-AREA (X . Y) TIMESTAMP
           OBJECT TEXT-POS (COL . ROW)
           IMAGE (DX . DY) (WIDTH . HEIGHT))

     The meanings of these list elements are documented below.  *Note
     Accessing Mouse::, for functions that let you easily access these
     elements.

    WINDOW
          This is the window in which the click occurred.

    POS-OR-AREA
          This is the buffer position of the character clicked on in
          the text area, or if clicked outside the text area, it is the
          window area in which the click occurred.  It is one of the
          symbols `mode-line', `header-line', `vertical-line',
          `left-margin', `right-margin', `left-fringe', or
          `right-fringe'.

          In one special case, POS-OR-AREA is a list containing a symbol
          (one of the symbols listed above) instead of just the symbol.
          This happens after the imaginary prefix keys for the event
          are registered by Emacs.  *Note Key Sequence Input::.

    X, Y
          These are the relative pixel coordinates of the click.  For
          clicks in the text area of a window, the coordinate origin
          `(0 . 0)' is taken to be the top left corner of the text
          area.  *Note Window Sizes::.  For clicks in a mode line or
          header line, the coordinate origin is the top left corner of
          the window itself.  For fringes, margins, and the vertical
          border, X does not have meaningful data.  For fringes and
          margins, Y is relative to the bottom edge of the header line.
          In all cases, the X and Y coordinates increase rightward and
          downward respectively.

    TIMESTAMP
          This is the time at which the event occurred, in milliseconds.

    OBJECT
          This is either `nil' if there is no string-type text property
          at the click position, or a cons cell of the form (STRING .
          STRING-POS) if there is one:

         STRING
               The string which was clicked on, including any
               properties.

         STRING-POS
               The position in the string where the click occurred.

    TEXT-POS
          For clicks on a marginal area or on a fringe, this is the
          buffer position of the first visible character in the
          corresponding line in the window.  For other events, it is
          the current buffer position in the window.

    COL, ROW
          These are the actual column and row coordinate numbers of the
          glyph under the X, Y position.  If X lies beyond the last
          column of actual text on its line, COL is reported by adding
          fictional extra columns that have the default character
          width.  Row 0 is taken to be the header line if the window
          has one, or the topmost row of the text area otherwise.
          Column 0 is taken to be the leftmost column of the text area
          for clicks on a window text area, or the leftmost mode line
          or header line column for clicks there.  For clicks on
          fringes or vertical borders, these have no meaningful data.
          For clicks on margins, COL is measured from the left edge of
          the margin area and ROW is measured from the top of the
          margin area.

    IMAGE
          This is the image object on which the click occurred.  It is
          either `nil' if there is no image at the position clicked on,
          or it is an image object as returned by `find-image' if click
          was in an image.

    DX, DY
          These are the pixel coordinates of the click, relative to the
          top left corner of OBJECT, which is `(0 . 0)'.  If OBJECT is
          `nil', the coordinates are relative to the top left corner of
          the character glyph clicked on.

    WIDTH, HEIGHT
          These are the pixel width and height of OBJECT or, if this is
          `nil', those of the character glyph clicked on.


     For mouse clicks on a scroll-bar, POSITION has this form:

          (WINDOW AREA (PORTION . WHOLE) TIMESTAMP PART)

    WINDOW
          This is the window whose scroll-bar was clicked on.

    AREA
          This is the scroll bar where the click occurred.  It is one
          of the symbols `vertical-scroll-bar' or
          `horizontal-scroll-bar'.

    PORTION
          This is the distance of the click from the top or left end of
          the scroll bar.

    WHOLE
          This is the length of the entire scroll bar.

    TIMESTAMP
          This is the time at which the event occurred, in milliseconds.

    PART
          This is the part of the scroll-bar which was clicked on.  It
          is one of the symbols `above-handle', `handle',
          `below-handle', `up', `down', `top', `bottom', and
          `end-scroll'.

CLICK-COUNT
     This is the number of rapid repeated presses so far of the same
     mouse button.  *Note Repeat Events::.


File: elisp,  Node: Drag Events,  Next: Button-Down Events,  Prev: Click Events,  Up: Input Events

21.7.5 Drag Events
------------------

With Emacs, you can have a drag event without even changing your
clothes.  A "drag event" happens every time the user presses a mouse
button and then moves the mouse to a different character position before
releasing the button.  Like all mouse events, drag events are
represented in Lisp as lists.  The lists record both the starting mouse
position and the final position, like this:

     (EVENT-TYPE
      (WINDOW1 START-POSITION)
      (WINDOW2 END-POSITION))

   For a drag event, the name of the symbol EVENT-TYPE contains the
prefix `drag-'.  For example, dragging the mouse with button 2 held
down generates a `drag-mouse-2' event.  The second and third elements
of the event give the starting and ending position of the drag.  They
have the same form as POSITION in a click event (*note Click Events::)
that is not on the scroll bar part of the window.  You can access the
second element of any mouse event in the same way, with no need to
distinguish drag events from others.

   The `drag-' prefix follows the modifier key prefixes such as `C-'
and `M-'.

   If `read-key-sequence' receives a drag event that has no key
binding, and the corresponding click event does have a binding, it
changes the drag event into a click event at the drag's starting
position.  This means that you don't have to distinguish between click
and drag events unless you want to.


File: elisp,  Node: Button-Down Events,  Next: Repeat Events,  Prev: Drag Events,  Up: Input Events

21.7.6 Button-Down Events
-------------------------

Click and drag events happen when the user releases a mouse button.
They cannot happen earlier, because there is no way to distinguish a
click from a drag until the button is released.

   If you want to take action as soon as a button is pressed, you need
to handle "button-down" events.(1)  These occur as soon as a button is
pressed.  They are represented by lists that look exactly like click
events (*note Click Events::), except that the EVENT-TYPE symbol name
contains the prefix `down-'.  The `down-' prefix follows modifier key
prefixes such as `C-' and `M-'.

   The function `read-key-sequence' ignores any button-down events that
don't have command bindings; therefore, the Emacs command loop ignores
them too.  This means that you need not worry about defining
button-down events unless you want them to do something.  The usual
reason to define a button-down event is so that you can track mouse
motion (by reading motion events) until the button is released.  *Note
Motion Events::.

   ---------- Footnotes ----------

   (1) Button-down is the conservative antithesis of drag.


File: elisp,  Node: Repeat Events,  Next: Motion Events,  Prev: Button-Down Events,  Up: Input Events

21.7.7 Repeat Events
--------------------

If you press the same mouse button more than once in quick succession
without moving the mouse, Emacs generates special "repeat" mouse events
for the second and subsequent presses.

   The most common repeat events are "double-click" events.  Emacs
generates a double-click event when you click a button twice; the event
happens when you release the button (as is normal for all click events).

   The event type of a double-click event contains the prefix
`double-'.  Thus, a double click on the second mouse button with <meta>
held down comes to the Lisp program as `M-double-mouse-2'.  If a
double-click event has no binding, the binding of the corresponding
ordinary click event is used to execute it.  Thus, you need not pay
attention to the double click feature unless you really want to.

   When the user performs a double click, Emacs generates first an
ordinary click event, and then a double-click event.  Therefore, you
must design the command binding of the double click event to assume
that the single-click command has already run.  It must produce the
desired results of a double click, starting from the results of a
single click.

   This is convenient, if the meaning of a double click somehow "builds
on" the meaning of a single click--which is recommended user interface
design practice for double clicks.

   If you click a button, then press it down again and start moving the
mouse with the button held down, then you get a "double-drag" event
when you ultimately release the button.  Its event type contains
`double-drag' instead of just `drag'.  If a double-drag event has no
binding, Emacs looks for an alternate binding as if the event were an
ordinary drag.

   Before the double-click or double-drag event, Emacs generates a
"double-down" event when the user presses the button down for the
second time.  Its event type contains `double-down' instead of just
`down'.  If a double-down event has no binding, Emacs looks for an
alternate binding as if the event were an ordinary button-down event.
If it finds no binding that way either, the double-down event is
ignored.

   To summarize, when you click a button and then press it again right
away, Emacs generates a down event and a click event for the first
click, a double-down event when you press the button again, and finally
either a double-click or a double-drag event.

   If you click a button twice and then press it again, all in quick
succession, Emacs generates a "triple-down" event, followed by either a
"triple-click" or a "triple-drag".  The event types of these events
contain `triple' instead of `double'.  If any triple event has no
binding, Emacs uses the binding that it would use for the corresponding
double event.

   If you click a button three or more times and then press it again,
the events for the presses beyond the third are all triple events.
Emacs does not have separate event types for quadruple, quintuple, etc.
events.  However, you can look at the event list to find out precisely
how many times the button was pressed.

 -- Function: event-click-count event
     This function returns the number of consecutive button presses
     that led up to EVENT.  If EVENT is a double-down, double-click or
     double-drag event, the value is 2.  If EVENT is a triple event,
     the value is 3 or greater.  If EVENT is an ordinary mouse event
     (not a repeat event), the value is 1.

 -- User Option: double-click-fuzz
     To generate repeat events, successive mouse button presses must be
     at approximately the same screen position.  The value of
     `double-click-fuzz' specifies the maximum number of pixels the
     mouse may be moved (horizontally or vertically) between two
     successive clicks to make a double-click.

     This variable is also the threshold for motion of the mouse to
     count as a drag.

 -- User Option: double-click-time
     To generate repeat events, the number of milliseconds between
     successive button presses must be less than the value of
     `double-click-time'.  Setting `double-click-time' to `nil'
     disables multi-click detection entirely.  Setting it to `t'
     removes the time limit; Emacs then detects multi-clicks by
     position only.


File: elisp,  Node: Motion Events,  Next: Focus Events,  Prev: Repeat Events,  Up: Input Events

21.7.8 Motion Events
--------------------

Emacs sometimes generates "mouse motion" events to describe motion of
the mouse without any button activity.  Mouse motion events are
represented by lists that look like this:

     (mouse-movement POSITION)

   The second element of the list describes the current position of the
mouse, just as in a click event (*note Click Events::).

   The special form `track-mouse' enables generation of motion events
within its body.  Outside of `track-mouse' forms, Emacs does not
generate events for mere motion of the mouse, and these events do not
appear.  *Note Mouse Tracking::.


File: elisp,  Node: Focus Events,  Next: Misc Events,  Prev: Motion Events,  Up: Input Events

21.7.9 Focus Events
-------------------

Window systems provide general ways for the user to control which window
gets keyboard input.  This choice of window is called the "focus".
When the user does something to switch between Emacs frames, that
generates a "focus event".  The normal definition of a focus event, in
the global keymap, is to select a new frame within Emacs, as the user
would expect.  *Note Input Focus::.

   Focus events are represented in Lisp as lists that look like this:

     (switch-frame NEW-FRAME)

where NEW-FRAME is the frame switched to.

   Some X window managers are set up so that just moving the mouse into
a window is enough to set the focus there.  Usually, there is no need
for a Lisp program to know about the focus change until some other kind
of input arrives.  Emacs generates a focus event only when the user
actually types a keyboard key or presses a mouse button in the new
frame; just moving the mouse between frames does not generate a focus
event.

   A focus event in the middle of a key sequence would garble the
sequence.  So Emacs never generates a focus event in the middle of a key
sequence.  If the user changes focus in the middle of a key
sequence--that is, after a prefix key--then Emacs reorders the events
so that the focus event comes either before or after the multi-event key
sequence, and not within it.


File: elisp,  Node: Misc Events,  Next: Event Examples,  Prev: Focus Events,  Up: Input Events

21.7.10 Miscellaneous System Events
-----------------------------------

A few other event types represent occurrences within the system.

`(delete-frame (FRAME))'
     This kind of event indicates that the user gave the window manager
     a command to delete a particular window, which happens to be an
     Emacs frame.

     The standard definition of the `delete-frame' event is to delete
     FRAME.

`(iconify-frame (FRAME))'
     This kind of event indicates that the user iconified FRAME using
     the window manager.  Its standard definition is `ignore'; since the
     frame has already been iconified, Emacs has no work to do.  The
     purpose of this event type is so that you can keep track of such
     events if you want to.

`(make-frame-visible (FRAME))'
     This kind of event indicates that the user deiconified FRAME using
     the window manager.  Its standard definition is `ignore'; since the
     frame has already been made visible, Emacs has no work to do.

`(wheel-up POSITION)'

`(wheel-down POSITION)'
     These kinds of event are generated by moving a mouse wheel.  Their
     usual meaning is a kind of scroll or zoom.

     The element POSITION is a list describing the position of the
     event, in the same format as used in a mouse-click event (*note
     Click Events::).

     This kind of event is generated only on some kinds of systems. On
     some systems, `mouse-4' and `mouse-5' are used instead.  For
     portable code, use the variables `mouse-wheel-up-event' and
     `mouse-wheel-down-event' defined in `mwheel.el' to determine what
     event types to expect for the mouse wheel.

`(drag-n-drop POSITION FILES)'
     This kind of event is generated when a group of files is selected
     in an application outside of Emacs, and then dragged and dropped
     onto an Emacs frame.

     The element POSITION is a list describing the position of the
     event, in the same format as used in a mouse-click event (*note
     Click Events::), and FILES is the list of file names that were
     dragged and dropped.  The usual way to handle this event is by
     visiting these files.

     This kind of event is generated, at present, only on some kinds of
     systems.

`help-echo'
     This kind of event is generated when a mouse pointer moves onto a
     portion of buffer text which has a `help-echo' text property.  The
     generated event has this form:

          (help-echo FRAME HELP WINDOW OBJECT POS)

     The precise meaning of the event parameters and the way these
     parameters are used to display the help-echo text are described in
     *note Text help-echo::.

`sigusr1'
`sigusr2'
     These events are generated when the Emacs process receives the
     signals `SIGUSR1' and `SIGUSR2'.  They contain no additional data
     because signals do not carry additional information.  They can be
     useful for debugging (*note Error Debugging::).

     To catch a user signal, bind the corresponding event to an
     interactive command in the `special-event-map' (*note Active
     Keymaps::).  The command is called with no arguments, and the
     specific signal event is available in `last-input-event'.  For
     example:

          (defun sigusr-handler ()
            (interactive)
            (message "Caught signal %S" last-input-event))

          (define-key special-event-map [sigusr1] 'sigusr-handler)

     To test the signal handler, you can make Emacs send a signal to
     itself:

          (signal-process (emacs-pid) 'sigusr1)

   If one of these events arrives in the middle of a key sequence--that
is, after a prefix key--then Emacs reorders the events so that this
event comes either before or after the multi-event key sequence, not
within it.


File: elisp,  Node: Event Examples,  Next: Classifying Events,  Prev: Misc Events,  Up: Input Events

21.7.11 Event Examples
----------------------

If the user presses and releases the left mouse button over the same
location, that generates a sequence of events like this:

     (down-mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864320))
     (mouse-1      (#<window 18 on NEWS> 2613 (0 . 38) -864180))

   While holding the control key down, the user might hold down the
second mouse button, and drag the mouse from one line to the next.
That produces two events, as shown here:

     (C-down-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219))
     (C-drag-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219)
                     (#<window 18 on NEWS> 3510 (0 . 28) -729648))

   While holding down the meta and shift keys, the user might press the
second mouse button on the window's mode line, and then drag the mouse
into another window.  That produces a pair of events like these:

     (M-S-down-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844))
     (M-S-drag-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844)
                       (#<window 20 on carlton-sanskrit.tex> 161 (33 . 3)
                        -453816))

   To handle a SIGUSR1 signal, define an interactive function, and bind
it to the `signal usr1' event sequence:

     (defun usr1-handler ()
       (interactive)
       (message "Got USR1 signal"))
     (global-set-key [signal usr1] 'usr1-handler)


File: elisp,  Node: Classifying Events,  Next: Accessing Mouse,  Prev: Event Examples,  Up: Input Events

21.7.12 Classifying Events
--------------------------

Every event has an "event type", which classifies the event for key
binding purposes.  For a keyboard event, the event type equals the
event value; thus, the event type for a character is the character, and
the event type for a function key symbol is the symbol itself.  For
events that are lists, the event type is the symbol in the CAR of the
list.  Thus, the event type is always a symbol or a character.

   Two events of the same type are equivalent where key bindings are
concerned; thus, they always run the same command.  That does not
necessarily mean they do the same things, however, as some commands look
at the whole event to decide what to do.  For example, some commands use
the location of a mouse event to decide where in the buffer to act.

   Sometimes broader classifications of events are useful.  For example,
you might want to ask whether an event involved the <META> key,
regardless of which other key or mouse button was used.

   The functions `event-modifiers' and `event-basic-type' are provided
to get such information conveniently.

 -- Function: event-modifiers event
     This function returns a list of the modifiers that EVENT has.  The
     modifiers are symbols; they include `shift', `control', `meta',
     `alt', `hyper' and `super'.  In addition, the modifiers list of a
     mouse event symbol always contains one of `click', `drag', and
     `down'.  For double or triple events, it also contains `double' or
     `triple'.

     The argument EVENT may be an entire event object, or just an event
     type.  If EVENT is a symbol that has never been used in an event
     that has been read as input in the current Emacs session, then
     `event-modifiers' can return `nil', even when EVENT actually has
     modifiers.

     Here are some examples:

          (event-modifiers ?a)
               => nil
          (event-modifiers ?A)
               => (shift)
          (event-modifiers ?\C-a)
               => (control)
          (event-modifiers ?\C-%)
               => (control)
          (event-modifiers ?\C-\S-a)
               => (control shift)
          (event-modifiers 'f5)
               => nil
          (event-modifiers 's-f5)
               => (super)
          (event-modifiers 'M-S-f5)
               => (meta shift)
          (event-modifiers 'mouse-1)
               => (click)
          (event-modifiers 'down-mouse-1)
               => (down)

     The modifiers list for a click event explicitly contains `click',
     but the event symbol name itself does not contain `click'.

 -- Function: event-basic-type event
     This function returns the key or mouse button that EVENT
     describes, with all modifiers removed.  The EVENT argument is as
     in `event-modifiers'.  For example:

          (event-basic-type ?a)
               => 97
          (event-basic-type ?A)
               => 97
          (event-basic-type ?\C-a)
               => 97
          (event-basic-type ?\C-\S-a)
               => 97
          (event-basic-type 'f5)
               => f5
          (event-basic-type 's-f5)
               => f5
          (event-basic-type 'M-S-f5)
               => f5
          (event-basic-type 'down-mouse-1)
               => mouse-1

 -- Function: mouse-movement-p object
     This function returns non-`nil' if OBJECT is a mouse movement
     event.

 -- Function: event-convert-list list
     This function converts a list of modifier names and a basic event
     type to an event type which specifies all of them.  The basic
     event type must be the last element of the list.  For example,

          (event-convert-list '(control ?a))
               => 1
          (event-convert-list '(control meta ?a))
               => -134217727
          (event-convert-list '(control super f1))
               => C-s-f1


File: elisp,  Node: Accessing Mouse,  Next: Accessing Scroll,  Prev: Classifying Events,  Up: Input Events

21.7.13 Accessing Mouse Events
------------------------------

This section describes convenient functions for accessing the data in a
mouse button or motion event.

   These two functions return the starting or ending position of a
mouse-button event, as a list of this form (*note Click Events::):

     (WINDOW POS-OR-AREA (X . Y) TIMESTAMP
      OBJECT TEXT-POS (COL . ROW)
      IMAGE (DX . DY) (WIDTH . HEIGHT))

 -- Function: event-start event
     This returns the starting position of EVENT.

     If EVENT is a click or button-down event, this returns the
     location of the event.  If EVENT is a drag event, this returns the
     drag's starting position.

 -- Function: event-end event
     This returns the ending position of EVENT.

     If EVENT is a drag event, this returns the position where the user
     released the mouse button.  If EVENT is a click or button-down
     event, the value is actually the starting position, which is the
     only position such events have.

   These functions take a position list as described above, and return
various parts of it.

 -- Function: posn-window position
     Return the window that POSITION is in.

 -- Function: posn-area position
     Return the window area recorded in POSITION.  It returns `nil'
     when the event occurred in the text area of the window; otherwise,
     it is a symbol identifying the area in which the event occurred.

 -- Function: posn-point position
     Return the buffer position in POSITION.  When the event occurred
     in the text area of the window, in a marginal area, or on a fringe,
     this is an integer specifying a buffer position.  Otherwise, the
     value is undefined.

 -- Function: posn-x-y position
     Return the pixel-based x and y coordinates in POSITION, as a cons
     cell `(X . Y)'.  These coordinates are relative to the window
     given by `posn-window'.

     This example shows how to convert the window-relative coordinates
     in the text area of a window into frame-relative coordinates:

          (defun frame-relative-coordinates (position)
            "Return frame-relative coordinates from POSITION.
          POSITION is assumed to lie in a window text area."
            (let* ((x-y (posn-x-y position))
                   (window (posn-window position))
                   (edges (window-inside-pixel-edges window)))
              (cons (+ (car x-y) (car edges))
                    (+ (cdr x-y) (cadr edges)))))

 -- Function: posn-col-row position
     This function returns a cons cell `(COL .  ROW)', containing the
     estimated column and row corresponding to buffer position
     POSITION.  The return value is given in units of the frame's
     default character width and height, as computed from the X and Y
     values corresponding to POSITION.  (So, if the actual characters
     have non-default sizes, the actual row and column may differ from
     these computed values.)

     Note that ROW is counted from the top of the text area.  If the
     window possesses a header line (*note Header Lines::), it is _not_
     counted as the first line.

 -- Function: posn-actual-col-row position
     Return the actual row and column in POSITION, as a cons cell `(COL
     . ROW)'.  The values are the actual row and column numbers in the
     window.  *Note Click Events::, for details.  It returns `nil' if
     POSITION does not include actual positions values.

 -- Function: posn-string position
     Return the string object in POSITION, either `nil', or a cons cell
     `(STRING . STRING-POS)'.

 -- Function: posn-image position
     Return the image object in POSITION, either `nil', or an image
     `(image ...)'.

 -- Function: posn-object position
     Return the image or string object in POSITION, either `nil', an
     image `(image ...)', or a cons cell `(STRING . STRING-POS)'.

 -- Function: posn-object-x-y position
     Return the pixel-based x and y coordinates relative to the upper
     left corner of the object in POSITION as a cons cell `(DX . DY)'.
     If the POSITION is a buffer position, return the relative position
     in the character at that position.

 -- Function: posn-object-width-height position
     Return the pixel width and height of the object in POSITION as a
     cons cell `(WIDTH . HEIGHT)'.  If the POSITION is a buffer
     position, return the size of the character at that position.

 -- Function: posn-timestamp position
     Return the timestamp in POSITION.  This is the time at which the
     event occurred, in milliseconds.

   These functions compute a position list given particular buffer
position or screen position.  You can access the data in this position
list with the functions described above.

 -- Function: posn-at-point &optional pos window
     This function returns a position list for position POS in WINDOW.
     POS defaults to point in WINDOW; WINDOW defaults to the selected
     window.

     `posn-at-point' returns `nil' if POS is not visible in WINDOW.

 -- Function: posn-at-x-y x y &optional frame-or-window whole
     This function returns position information corresponding to pixel
     coordinates X and Y in a specified frame or window,
     FRAME-OR-WINDOW, which defaults to the selected window.  The
     coordinates X and Y are relative to the frame or window used.  If
     WHOLE is `nil', the coordinates are relative to the window text
     area, otherwise they are relative to the entire window area
     including scroll bars, margins and fringes.


File: elisp,  Node: Accessing Scroll,  Next: Strings of Events,  Prev: Accessing Mouse,  Up: Input Events

21.7.14 Accessing Scroll Bar Events
-----------------------------------

These functions are useful for decoding scroll bar events.

 -- Function: scroll-bar-event-ratio event
     This function returns the fractional vertical position of a scroll
     bar event within the scroll bar.  The value is a cons cell
     `(PORTION . WHOLE)' containing two integers whose ratio is the
     fractional position.

 -- Function: scroll-bar-scale ratio total
     This function multiplies (in effect) RATIO by TOTAL, rounding the
     result to an integer.  The argument RATIO is not a number, but
     rather a pair `(NUM . DENOM)'--typically a value returned by
     `scroll-bar-event-ratio'.

     This function is handy for scaling a position on a scroll bar into
     a buffer position.  Here's how to do that:

          (+ (point-min)
             (scroll-bar-scale
                (posn-x-y (event-start event))
                (- (point-max) (point-min))))

     Recall that scroll bar events have two integers forming a ratio,
     in place of a pair of x and y coordinates.


File: elisp,  Node: Strings of Events,  Prev: Accessing Scroll,  Up: Input Events

21.7.15 Putting Keyboard Events in Strings
------------------------------------------

In most of the places where strings are used, we conceptualize the
string as containing text characters--the same kind of characters found
in buffers or files.  Occasionally Lisp programs use strings that
conceptually contain keyboard characters; for example, they may be key
sequences or keyboard macro definitions.  However, storing keyboard
characters in a string is a complex matter, for reasons of historical
compatibility, and it is not always possible.

   We recommend that new programs avoid dealing with these complexities
by not storing keyboard events in strings.  Here is how to do that:

   * Use vectors instead of strings for key sequences, when you plan to
     use them for anything other than as arguments to `lookup-key' and
     `define-key'.  For example, you can use `read-key-sequence-vector'
     instead of `read-key-sequence', and `this-command-keys-vector'
     instead of `this-command-keys'.

   * Use vectors to write key sequence constants containing meta
     characters, even when passing them directly to `define-key'.

   * When you have to look at the contents of a key sequence that might
     be a string, use `listify-key-sequence' (*note Event Input Misc::)
     first, to convert it to a list.

   The complexities stem from the modifier bits that keyboard input
characters can include.  Aside from the Meta modifier, none of these
modifier bits can be included in a string, and the Meta modifier is
allowed only in special cases.

   The earliest GNU Emacs versions represented meta characters as codes
in the range of 128 to 255.  At that time, the basic character codes
ranged from 0 to 127, so all keyboard character codes did fit in a
string.  Many Lisp programs used `\M-' in string constants to stand for
meta characters, especially in arguments to `define-key' and similar
functions, and key sequences and sequences of events were always
represented as strings.

   When we added support for larger basic character codes beyond 127,
and additional modifier bits, we had to change the representation of
meta characters.  Now the flag that represents the Meta modifier in a
character is 2**27 and such numbers cannot be included in a string.

   To support programs with `\M-' in string constants, there are
special rules for including certain meta characters in a string.  Here
are the rules for interpreting a string as a sequence of input
characters:

   * If the keyboard character value is in the range of 0 to 127, it
     can go in the string unchanged.

   * The meta variants of those characters, with codes in the range of
     2**27 to 2**27+127, can also go in the string, but you must change
     their numeric values.  You must set the 2**7 bit instead of the
     2**27 bit, resulting in a value between 128 and 255.  Only a
     unibyte string can include these codes.

   * Non-ASCII characters above 256 can be included in a multibyte
     string.

   * Other keyboard character events cannot fit in a string.  This
     includes keyboard events in the range of 128 to 255.

   Functions such as `read-key-sequence' that construct strings of
keyboard input characters follow these rules: they construct vectors
instead of strings, when the events won't fit in a string.

   When you use the read syntax `\M-' in a string, it produces a code
in the range of 128 to 255--the same code that you get if you modify
the corresponding keyboard event to put it in the string.  Thus, meta
events in strings work consistently regardless of how they get into the
strings.

   However, most programs would do well to avoid these issues by
following the recommendations at the beginning of this section.


File: elisp,  Node: Reading Input,  Next: Special Events,  Prev: Input Events,  Up: Command Loop

21.8 Reading Input
==================

The editor command loop reads key sequences using the function
`read-key-sequence', which uses `read-event'.  These and other
functions for event input are also available for use in Lisp programs.
See also `momentary-string-display' in *note Temporary Displays::, and
`sit-for' in *note Waiting::.  *Note Terminal Input::, for functions
and variables for controlling terminal input modes and debugging
terminal input.

   For higher-level input facilities, see *note Minibuffers::.

* Menu:

* Key Sequence Input::          How to read one key sequence.
* Reading One Event::           How to read just one event.
* Event Mod::                   How Emacs modifies events as they are read.
* Invoking the Input Method::   How reading an event uses the input method.
* Quoted Character Input::      Asking the user to specify a character.
* Event Input Misc::            How to reread or throw away input events.


File: elisp,  Node: Key Sequence Input,  Next: Reading One Event,  Up: Reading Input

21.8.1 Key Sequence Input
-------------------------

The command loop reads input a key sequence at a time, by calling
`read-key-sequence'.  Lisp programs can also call this function; for
example, `describe-key' uses it to read the key to describe.

 -- Function: read-key-sequence prompt &optional continue-echo
          dont-downcase-last switch-frame-ok command-loop
     This function reads a key sequence and returns it as a string or
     vector.  It keeps reading events until it has accumulated a
     complete key sequence; that is, enough to specify a non-prefix
     command using the currently active keymaps.  (Remember that a key
     sequence that starts with a mouse event is read using the keymaps
     of the buffer in the window that the mouse was in, not the current
     buffer.)

     If the events are all characters and all can fit in a string, then
     `read-key-sequence' returns a string (*note Strings of Events::).
     Otherwise, it returns a vector, since a vector can hold all kinds
     of events--characters, symbols, and lists.  The elements of the
     string or vector are the events in the key sequence.

     Reading a key sequence includes translating the events in various
     ways.  *Note Translation Keymaps::.

     The argument PROMPT is either a string to be displayed in the echo
     area as a prompt, or `nil', meaning not to display a prompt.  The
     argument CONTINUE-ECHO, if non-`nil', means to echo this key as a
     continuation of the previous key.

     Normally any upper case event is converted to lower case if the
     original event is undefined and the lower case equivalent is
     defined.  The argument DONT-DOWNCASE-LAST, if non-`nil', means do
     not convert the last event to lower case.  This is appropriate for
     reading a key sequence to be defined.

     The argument SWITCH-FRAME-OK, if non-`nil', means that this
     function should process a `switch-frame' event if the user
     switches frames before typing anything.  If the user switches
     frames in the middle of a key sequence, or at the start of the
     sequence but SWITCH-FRAME-OK is `nil', then the event will be put
     off until after the current key sequence.

     The argument COMMAND-LOOP, if non-`nil', means that this key
     sequence is being read by something that will read commands one
     after another.  It should be `nil' if the caller will read just
     one key sequence.

     In the following example, Emacs displays the prompt `?' in the
     echo area, and then the user types `C-x C-f'.

          (read-key-sequence "?")

          ---------- Echo Area ----------
          ?C-x C-f
          ---------- Echo Area ----------

               => "^X^F"

     The function `read-key-sequence' suppresses quitting: `C-g' typed
     while reading with this function works like any other character,
     and does not set `quit-flag'.  *Note Quitting::.

 -- Function: read-key-sequence-vector prompt &optional continue-echo
          dont-downcase-last switch-frame-ok command-loop
     This is like `read-key-sequence' except that it always returns the
     key sequence as a vector, never as a string.  *Note Strings of
     Events::.

   If an input character is upper-case (or has the shift modifier) and
has no key binding, but its lower-case equivalent has one, then
`read-key-sequence' converts the character to lower case.  Note that
`lookup-key' does not perform case conversion in this way.

   When reading input results in such a "shift-translation", Emacs sets
the variable `this-command-keys-shift-translated' to a non-`nil' value.
Lisp programs can examine this variable if they need to modify their
behavior when invoked by shift-translated keys.  For example, the
function `handle-shift-selection' examines the value of this variable
to determine how to activate or deactivate the region (*note
handle-shift-selection: The Mark.).

   The function `read-key-sequence' also transforms some mouse events.
It converts unbound drag events into click events, and discards unbound
button-down events entirely.  It also reshuffles focus events and
miscellaneous window events so that they never appear in a key sequence
with any other events.

   When mouse events occur in special parts of a window, such as a mode
line or a scroll bar, the event type shows nothing special--it is the
same symbol that would normally represent that combination of mouse
button and modifier keys.  The information about the window part is kept
elsewhere in the event--in the coordinates.  But `read-key-sequence'
translates this information into imaginary "prefix keys", all of which
are symbols: `header-line', `horizontal-scroll-bar', `menu-bar',
`mode-line', `vertical-line', and `vertical-scroll-bar'.  You can define
meanings for mouse clicks in special window parts by defining key
sequences using these imaginary prefix keys.

   For example, if you call `read-key-sequence' and then click the
mouse on the window's mode line, you get two events, like this:

     (read-key-sequence "Click on the mode line: ")
          => [mode-line
              (mouse-1
               (#<window 6 on NEWS> mode-line
                (40 . 63) 5959987))]

 -- Variable: num-input-keys
     This variable's value is the number of key sequences processed so
     far in this Emacs session.  This includes key sequences read from
     the terminal and key sequences read from keyboard macros being
     executed.


File: elisp,  Node: Reading One Event,  Next: Event Mod,  Prev: Key Sequence Input,  Up: Reading Input

21.8.2 Reading One Event
------------------------

The lowest level functions for command input are `read-event',
`read-char', and `read-char-exclusive'.

 -- Function: read-event &optional prompt inherit-input-method seconds
     This function reads and returns the next event of command input,
     waiting if necessary until an event is available.  Events can come
     directly from the user or from a keyboard macro.

     If the optional argument PROMPT is non-`nil', it should be a
     string to display in the echo area as a prompt.  Otherwise,
     `read-event' does not display any message to indicate it is waiting
     for input; instead, it prompts by echoing: it displays
     descriptions of the events that led to or were read by the current
     command.  *Note The Echo Area::.

     If INHERIT-INPUT-METHOD is non-`nil', then the current input
     method (if any) is employed to make it possible to enter a
     non-ASCII character.  Otherwise, input method handling is disabled
     for reading this event.

     If `cursor-in-echo-area' is non-`nil', then `read-event' moves the
     cursor temporarily to the echo area, to the end of any message
     displayed there.  Otherwise `read-event' does not move the cursor.

     If SECONDS is non-`nil', it should be a number specifying the
     maximum time to wait for input, in seconds.  If no input arrives
     within that time, `read-event' stops waiting and returns `nil'.  A
     floating-point value for SECONDS means to wait for a fractional
     number of seconds.  Some systems support only a whole number of
     seconds; on these systems, SECONDS is rounded down.  If SECONDS is
     `nil', `read-event' waits as long as necessary for input to arrive.

     If SECONDS is `nil', Emacs is considered idle while waiting for
     user input to arrive.  Idle timers--those created with
     `run-with-idle-timer' (*note Idle Timers::)--can run during this
     period.  However, if SECONDS is non-`nil', the state of idleness
     remains unchanged.  If Emacs is non-idle when `read-event' is
     called, it remains non-idle throughout the operation of
     `read-event'; if Emacs is idle (which can happen if the call
     happens inside an idle timer), it remains idle.

     If `read-event' gets an event that is defined as a help character,
     then in some cases `read-event' processes the event directly
     without returning.  *Note Help Functions::.  Certain other events,
     called "special events", are also processed directly within
     `read-event' (*note Special Events::).

     Here is what happens if you call `read-event' and then press the
     right-arrow function key:

          (read-event)
               => right

 -- Function: read-char &optional prompt inherit-input-method seconds
     This function reads and returns a character of command input.  If
     the user generates an event which is not a character (i.e. a mouse
     click or function key event), `read-char' signals an error.  The
     arguments work as in `read-event'.

     In the first example, the user types the character `1' (ASCII code
     49).  The second example shows a keyboard macro definition that
     calls `read-char' from the minibuffer using `eval-expression'.
     `read-char' reads the keyboard macro's very next character, which
     is `1'.  Then `eval-expression' displays its return value in the
     echo area.

          (read-char)
               => 49

          ;; We assume here you use `M-:' to evaluate this.
          (symbol-function 'foo)
               => "^[:(read-char)^M1"
          (execute-kbd-macro 'foo)
               -| 49
               => nil

 -- Function: read-char-exclusive &optional prompt inherit-input-method
          seconds
     This function reads and returns a character of command input.  If
     the user generates an event which is not a character,
     `read-char-exclusive' ignores it and reads another event, until it
     gets a character.  The arguments work as in `read-event'.

   None of the above functions suppress quitting.

 -- Variable: num-nonmacro-input-events
     This variable holds the total number of input events received so
     far from the terminal--not counting those generated by keyboard
     macros.

   We emphasize that, unlike `read-key-sequence', the functions
`read-event', `read-char', and `read-char-exclusive' do not perform the
translations described in *note Translation Keymaps::.  If you wish to
read a single key taking these translations into account, use the
function `read-key':

 -- Function: read-key &optional prompt
     This function reads a single key.  It is "intermediate" between
     `read-key-sequence' and `read-event'.  Unlike the former, it reads
     a single key, not a key sequence.  Unlike the latter, it does not
     return a raw event, but decodes and translates the user input
     according to `input-decode-map', `local-function-key-map', and
     `key-translation-map' (*note Translation Keymaps::).

     The argument PROMPT is either a string to be displayed in the echo
     area as a prompt, or `nil', meaning not to display a prompt.

 -- Function: read-char-choice prompt chars &optional inhibit-quit
     This function uses `read-key' to read and return a single
     character.  It ignores any input that is not a member of CHARS, a
     list of accepted characters.  Optionally, it will also ignore
     keyboard-quit events while it is waiting for valid input.  If you
     bind `help-form' (*note Help Functions::) to a non-`nil' value
     while calling `read-char-choice', then pressing `help-char' causes
     it to evaluate `help-form' and display the result.  It then
     continues to wait for a valid input character, or keyboard-quit.


File: elisp,  Node: Event Mod,  Next: Invoking the Input Method,  Prev: Reading One Event,  Up: Reading Input

21.8.3 Modifying and Translating Input Events
---------------------------------------------

Emacs modifies every event it reads according to
`extra-keyboard-modifiers', then translates it through
`keyboard-translate-table' (if applicable), before returning it from
`read-event'.

 -- Variable: extra-keyboard-modifiers
     This variable lets Lisp programs "press" the modifier keys on the
     keyboard.  The value is a character.  Only the modifiers of the
     character matter.  Each time the user types a keyboard key, it is
     altered as if those modifier keys were held down.  For instance, if
     you bind `extra-keyboard-modifiers' to `?\C-\M-a', then all
     keyboard input characters typed during the scope of the binding
     will have the control and meta modifiers applied to them.  The
     character `?\C-@', equivalent to the integer 0, does not count as
     a control character for this purpose, but as a character with no
     modifiers.  Thus, setting `extra-keyboard-modifiers' to zero
     cancels any modification.

     When using a window system, the program can "press" any of the
     modifier keys in this way.  Otherwise, only the <CTL> and <META>
     keys can be virtually pressed.

     Note that this variable applies only to events that really come
     from the keyboard, and has no effect on mouse events or any other
     events.

 -- Variable: keyboard-translate-table
     This terminal-local variable is the translate table for keyboard
     characters.  It lets you reshuffle the keys on the keyboard without
     changing any command bindings.  Its value is normally a
     char-table, or else `nil'.  (It can also be a string or vector,
     but this is considered obsolete.)

     If `keyboard-translate-table' is a char-table (*note
     Char-Tables::), then each character read from the keyboard is
     looked up in this char-table.  If the value found there is
     non-`nil', then it is used instead of the actual input character.

     Note that this translation is the first thing that happens to a
     character after it is read from the terminal.  Record-keeping
     features such as `recent-keys' and dribble files record the
     characters after translation.

     Note also that this translation is done before the characters are
     supplied to input methods (*note Input Methods::).  Use
     `translation-table-for-input' (*note Translation of Characters::),
     if you want to translate characters after input methods operate.

 -- Function: keyboard-translate from to
     This function modifies `keyboard-translate-table' to translate
     character code FROM into character code TO.  It creates the
     keyboard translate table if necessary.

   Here's an example of using the `keyboard-translate-table' to make
`C-x', `C-c' and `C-v' perform the cut, copy and paste operations:

     (keyboard-translate ?\C-x 'control-x)
     (keyboard-translate ?\C-c 'control-c)
     (keyboard-translate ?\C-v 'control-v)
     (global-set-key [control-x] 'kill-region)
     (global-set-key [control-c] 'kill-ring-save)
     (global-set-key [control-v] 'yank)

On a graphical terminal that supports extended ASCII input, you can
still get the standard Emacs meanings of one of those characters by
typing it with the shift key.  That makes it a different character as
far as keyboard translation is concerned, but it has the same usual
meaning.

   *Note Translation Keymaps::, for mechanisms that translate event
sequences at the level of `read-key-sequence'.


File: elisp,  Node: Invoking the Input Method,  Next: Quoted Character Input,  Prev: Event Mod,  Up: Reading Input

21.8.4 Invoking the Input Method
--------------------------------

The event-reading functions invoke the current input method, if any
(*note Input Methods::).  If the value of `input-method-function' is
non-`nil', it should be a function; when `read-event' reads a printing
character (including <SPC>) with no modifier bits, it calls that
function, passing the character as an argument.

 -- Variable: input-method-function
     If this is non-`nil', its value specifies the current input method
     function.

     *Warning:* don't bind this variable with `let'.  It is often
     buffer-local, and if you bind it around reading input (which is
     exactly when you _would_ bind it), switching buffers
     asynchronously while Emacs is waiting will cause the value to be
     restored in the wrong buffer.

   The input method function should return a list of events which should
be used as input.  (If the list is `nil', that means there is no input,
so `read-event' waits for another event.)  These events are processed
before the events in `unread-command-events' (*note Event Input
Misc::).  Events returned by the input method function are not passed
to the input method function again, even if they are printing
characters with no modifier bits.

   If the input method function calls `read-event' or
`read-key-sequence', it should bind `input-method-function' to `nil'
first, to prevent recursion.

   The input method function is not called when reading the second and
subsequent events of a key sequence.  Thus, these characters are not
subject to input method processing.  The input method function should
test the values of `overriding-local-map' and
`overriding-terminal-local-map'; if either of these variables is
non-`nil', the input method should put its argument into a list and
return that list with no further processing.


File: elisp,  Node: Quoted Character Input,  Next: Event Input Misc,  Prev: Invoking the Input Method,  Up: Reading Input

21.8.5 Quoted Character Input
-----------------------------

You can use the function `read-quoted-char' to ask the user to specify
a character, and allow the user to specify a control or meta character
conveniently, either literally or as an octal character code.  The
command `quoted-insert' uses this function.

 -- Function: read-quoted-char &optional prompt
     This function is like `read-char', except that if the first
     character read is an octal digit (0-7), it reads any number of
     octal digits (but stopping if a non-octal digit is found), and
     returns the character represented by that numeric character code.
     If the character that terminates the sequence of octal digits is
     <RET>, it is discarded.  Any other terminating character is used
     as input after this function returns.

     Quitting is suppressed when the first character is read, so that
     the user can enter a `C-g'.  *Note Quitting::.

     If PROMPT is supplied, it specifies a string for prompting the
     user.  The prompt string is always displayed in the echo area,
     followed by a single `-'.

     In the following example, the user types in the octal number 177
     (which is 127 in decimal).

          (read-quoted-char "What character")

          ---------- Echo Area ----------
          What character 1 7 7-
          ---------- Echo Area ----------

               => 127


File: elisp,  Node: Event Input Misc,  Prev: Quoted Character Input,  Up: Reading Input

21.8.6 Miscellaneous Event Input Features
-----------------------------------------

This section describes how to "peek ahead" at events without using them
up, how to check for pending input, and how to discard pending input.
See also the function `read-passwd' (*note Reading a Password::).

 -- Variable: unread-command-events
     This variable holds a list of events waiting to be read as command
     input.  The events are used in the order they appear in the list,
     and removed one by one as they are used.

     The variable is needed because in some cases a function reads an
     event and then decides not to use it.  Storing the event in this
     variable causes it to be processed normally, by the command loop
     or by the functions to read command input.

     For example, the function that implements numeric prefix arguments
     reads any number of digits.  When it finds a non-digit event, it
     must unread the event so that it can be read normally by the
     command loop.  Likewise, incremental search uses this feature to
     unread events with no special meaning in a search, because these
     events should exit the search and then execute normally.

     The reliable and easy way to extract events from a key sequence so
     as to put them in `unread-command-events' is to use
     `listify-key-sequence' (see below).

     Normally you add events to the front of this list, so that the
     events most recently unread will be reread first.

     Events read from this list are not normally added to the current
     command's key sequence (as returned by e.g. `this-command-keys'),
     as the events will already have been added once as they were read
     for the first time.  An element of the form `(`t' . EVENT)' forces
     EVENT to be added to the current command's key sequence.

 -- Function: listify-key-sequence key
     This function converts the string or vector KEY to a list of
     individual events, which you can put in `unread-command-events'.

 -- Function: input-pending-p
     This function determines whether any command input is currently
     available to be read.  It returns immediately, with value `t' if
     there is available input, `nil' otherwise.  On rare occasions it
     may return `t' when no input is available.

 -- Variable: last-input-event
 -- Variable: last-input-char
     This variable records the last terminal input event read, whether
     as part of a command or explicitly by a Lisp program.

     In the example below, the Lisp program reads the character `1',
     ASCII code 49.  It becomes the value of `last-input-event', while
     `C-e' (we assume `C-x C-e' command is used to evaluate this
     expression) remains the value of `last-command-event'.

          (progn (print (read-char))
                 (print last-command-event)
                 last-input-event)
               -| 49
               -| 5
               => 49

     The alias `last-input-char' is obsolete.

 -- Macro: while-no-input body...
     This construct runs the BODY forms and returns the value of the
     last one--but only if no input arrives.  If any input arrives
     during the execution of the BODY forms, it aborts them (working
     much like a quit).  The `while-no-input' form returns `nil' if
     aborted by a real quit, and returns `t' if aborted by arrival of
     other input.

     If a part of BODY binds `inhibit-quit' to non-`nil', arrival of
     input during those parts won't cause an abort until the end of
     that part.

     If you want to be able to distinguish all possible values computed
     by BODY from both kinds of abort conditions, write the code like
     this:

          (while-no-input
            (list
              (progn . BODY)))

 -- Function: discard-input
     This function discards the contents of the terminal input buffer
     and cancels any keyboard macro that might be in the process of
     definition.  It returns `nil'.

     In the following example, the user may type a number of characters
     right after starting the evaluation of the form.  After the
     `sleep-for' finishes sleeping, `discard-input' discards any
     characters typed during the sleep.

          (progn (sleep-for 2)
                 (discard-input))
               => nil


File: elisp,  Node: Special Events,  Next: Waiting,  Prev: Reading Input,  Up: Command Loop

21.9 Special Events
===================

Certain "special events" are handled at a very low level--as soon as
they are read.  The `read-event' function processes these events
itself, and never returns them.  Instead, it keeps waiting for the
first event that is not special and returns that one.

   Special events do not echo, they are never grouped into key
sequences, and they never appear in the value of `last-command-event'
or `(this-command-keys)'.  They do not discard a numeric argument, they
cannot be unread with `unread-command-events', they may not appear in a
keyboard macro, and they are not recorded in a keyboard macro while you
are defining one.

   Special events do, however, appear in `last-input-event' immediately
after they are read, and this is the way for the event's definition to
find the actual event.

   The events types `iconify-frame', `make-frame-visible',
`delete-frame', `drag-n-drop', and user signals like `sigusr1' are
normally handled in this way.  The keymap which defines how to handle
special events--and which events are special--is in the variable
`special-event-map' (*note Active Keymaps::).


File: elisp,  Node: Waiting,  Next: Quitting,  Prev: Special Events,  Up: Command Loop

21.10 Waiting for Elapsed Time or Input
=======================================

The wait functions are designed to wait for a certain amount of time to
pass or until there is input.  For example, you may wish to pause in
the middle of a computation to allow the user time to view the display.
`sit-for' pauses and updates the screen, and returns immediately if
input comes in, while `sleep-for' pauses without updating the screen.

 -- Function: sit-for seconds &optional nodisp
     This function performs redisplay (provided there is no pending
     input from the user), then waits SECONDS seconds, or until input is
     available.  The usual purpose of `sit-for' is to give the user
     time to read text that you display.  The value is `t' if `sit-for'
     waited the full time with no input arriving (*note Event Input
     Misc::).  Otherwise, the value is `nil'.

     The argument SECONDS need not be an integer.  If it is a floating
     point number, `sit-for' waits for a fractional number of seconds.
     Some systems support only a whole number of seconds; on these
     systems, SECONDS is rounded down.

     The expression `(sit-for 0)' is equivalent to `(redisplay)', i.e.
     it requests a redisplay, without any delay, if there is no pending
     input.  *Note Forcing Redisplay::.

     If NODISP is non-`nil', then `sit-for' does not redisplay, but it
     still returns as soon as input is available (or when the timeout
     elapses).

     In batch mode (*note Batch Mode::), `sit-for' cannot be
     interrupted, even by input from the standard input descriptor.  It
     is thus equivalent to `sleep-for', which is described below.

     It is also possible to call `sit-for' with three arguments, as
     `(sit-for SECONDS MILLISEC NODISP)', but that is considered
     obsolete.

 -- Function: sleep-for seconds &optional millisec
     This function simply pauses for SECONDS seconds without updating
     the display.  It pays no attention to available input.  It returns
     `nil'.

     The argument SECONDS need not be an integer.  If it is a floating
     point number, `sleep-for' waits for a fractional number of seconds.
     Some systems support only a whole number of seconds; on these
     systems, SECONDS is rounded down.

     The optional argument MILLISEC specifies an additional waiting
     period measured in milliseconds.  This adds to the period
     specified by SECONDS.  If the system doesn't support waiting
     fractions of a second, you get an error if you specify nonzero
     MILLISEC.

     Use `sleep-for' when you wish to guarantee a delay.

   *Note Time of Day::, for functions to get the current time.


File: elisp,  Node: Quitting,  Next: Prefix Command Arguments,  Prev: Waiting,  Up: Command Loop

21.11 Quitting
==============

Typing `C-g' while a Lisp function is running causes Emacs to "quit"
whatever it is doing.  This means that control returns to the innermost
active command loop.

   Typing `C-g' while the command loop is waiting for keyboard input
does not cause a quit; it acts as an ordinary input character.  In the
simplest case, you cannot tell the difference, because `C-g' normally
runs the command `keyboard-quit', whose effect is to quit.  However,
when `C-g' follows a prefix key, they combine to form an undefined key.
The effect is to cancel the prefix key as well as any prefix argument.

   In the minibuffer, `C-g' has a different definition: it aborts out
of the minibuffer.  This means, in effect, that it exits the minibuffer
and then quits.  (Simply quitting would return to the command loop
_within_ the minibuffer.)  The reason why `C-g' does not quit directly
when the command reader is reading input is so that its meaning can be
redefined in the minibuffer in this way.  `C-g' following a prefix key
is not redefined in the minibuffer, and it has its normal effect of
canceling the prefix key and prefix argument.  This too would not be
possible if `C-g' always quit directly.

   When `C-g' does directly quit, it does so by setting the variable
`quit-flag' to `t'.  Emacs checks this variable at appropriate times
and quits if it is not `nil'.  Setting `quit-flag' non-`nil' in any way
thus causes a quit.

   At the level of C code, quitting cannot happen just anywhere; only
at the special places that check `quit-flag'.  The reason for this is
that quitting at other places might leave an inconsistency in Emacs's
internal state.  Because quitting is delayed until a safe place,
quitting cannot make Emacs crash.

   Certain functions such as `read-key-sequence' or `read-quoted-char'
prevent quitting entirely even though they wait for input.  Instead of
quitting, `C-g' serves as the requested input.  In the case of
`read-key-sequence', this serves to bring about the special behavior of
`C-g' in the command loop.  In the case of `read-quoted-char', this is
so that `C-q' can be used to quote a `C-g'.

   You can prevent quitting for a portion of a Lisp function by binding
the variable `inhibit-quit' to a non-`nil' value.  Then, although `C-g'
still sets `quit-flag' to `t' as usual, the usual result of this--a
quit--is prevented.  Eventually, `inhibit-quit' will become `nil'
again, such as when its binding is unwound at the end of a `let' form.
At that time, if `quit-flag' is still non-`nil', the requested quit
happens immediately.  This behavior is ideal when you wish to make sure
that quitting does not happen within a "critical section" of the
program.

   In some functions (such as `read-quoted-char'), `C-g' is handled in
a special way that does not involve quitting.  This is done by reading
the input with `inhibit-quit' bound to `t', and setting `quit-flag' to
`nil' before `inhibit-quit' becomes `nil' again.  This excerpt from the
definition of `read-quoted-char' shows how this is done; it also shows
that normal quitting is permitted after the first character of input.

     (defun read-quoted-char (&optional prompt)
       "...DOCUMENTATION..."
       (let ((message-log-max nil) done (first t) (code 0) char)
         (while (not done)
           (let ((inhibit-quit first)
                 ...)
             (and prompt (message "%s-" prompt))
             (setq char (read-event))
             (if inhibit-quit (setq quit-flag nil)))
           ...set the variable `code'...)
         code))

 -- Variable: quit-flag
     If this variable is non-`nil', then Emacs quits immediately, unless
     `inhibit-quit' is non-`nil'.  Typing `C-g' ordinarily sets
     `quit-flag' non-`nil', regardless of `inhibit-quit'.

 -- Variable: inhibit-quit
     This variable determines whether Emacs should quit when `quit-flag'
     is set to a value other than `nil'.  If `inhibit-quit' is
     non-`nil', then `quit-flag' has no special effect.

 -- Macro: with-local-quit body...
     This macro executes BODY forms in sequence, but allows quitting, at
     least locally, within BODY even if `inhibit-quit' was non-`nil'
     outside this construct.  It returns the value of the last form in
     BODY, unless exited by quitting, in which case it returns `nil'.

     If `inhibit-quit' is `nil' on entry to `with-local-quit', it only
     executes the BODY, and setting `quit-flag' causes a normal quit.
     However, if `inhibit-quit' is non-`nil' so that ordinary quitting
     is delayed, a non-`nil' `quit-flag' triggers a special kind of
     local quit.  This ends the execution of BODY and exits the
     `with-local-quit' body with `quit-flag' still non-`nil', so that
     another (ordinary) quit will happen as soon as that is allowed.
     If `quit-flag' is already non-`nil' at the beginning of BODY, the
     local quit happens immediately and the body doesn't execute at all.

     This macro is mainly useful in functions that can be called from
     timers, process filters, process sentinels, `pre-command-hook',
     `post-command-hook', and other places where `inhibit-quit' is
     normally bound to `t'.

 -- Command: keyboard-quit
     This function signals the `quit' condition with `(signal 'quit
     nil)'.  This is the same thing that quitting does.  (See `signal'
     in *note Errors::.)

   You can specify a character other than `C-g' to use for quitting.
See the function `set-input-mode' in *note Terminal Input::.


File: elisp,  Node: Prefix Command Arguments,  Next: Recursive Editing,  Prev: Quitting,  Up: Command Loop

21.12 Prefix Command Arguments
==============================

Most Emacs commands can use a "prefix argument", a number specified
before the command itself.  (Don't confuse prefix arguments with prefix
keys.)  The prefix argument is at all times represented by a value,
which may be `nil', meaning there is currently no prefix argument.
Each command may use the prefix argument or ignore it.

   There are two representations of the prefix argument: "raw" and
"numeric".  The editor command loop uses the raw representation
internally, and so do the Lisp variables that store the information, but
commands can request either representation.

   Here are the possible values of a raw prefix argument:

   * `nil', meaning there is no prefix argument.  Its numeric value is
     1, but numerous commands make a distinction between `nil' and the
     integer 1.

   * An integer, which stands for itself.

   * A list of one element, which is an integer.  This form of prefix
     argument results from one or a succession of `C-u's with no
     digits.  The numeric value is the integer in the list, but some
     commands make a distinction between such a list and an integer
     alone.

   * The symbol `-'.  This indicates that `M--' or `C-u -' was typed,
     without following digits.  The equivalent numeric value is -1, but
     some commands make a distinction between the integer -1 and the
     symbol `-'.

   We illustrate these possibilities by calling the following function
with various prefixes:

     (defun display-prefix (arg)
       "Display the value of the raw prefix arg."
       (interactive "P")
       (message "%s" arg))

Here are the results of calling `display-prefix' with various raw
prefix arguments:

             M-x display-prefix  -| nil

     C-u     M-x display-prefix  -| (4)

     C-u C-u M-x display-prefix  -| (16)

     C-u 3   M-x display-prefix  -| 3

     M-3     M-x display-prefix  -| 3      ; (Same as `C-u 3'.)

     C-u -   M-x display-prefix  -| -

     M--     M-x display-prefix  -| -      ; (Same as `C-u -'.)

     C-u - 7 M-x display-prefix  -| -7

     M-- 7   M-x display-prefix  -| -7     ; (Same as `C-u -7'.)

   Emacs uses two variables to store the prefix argument: `prefix-arg'
and `current-prefix-arg'.  Commands such as `universal-argument' that
set up prefix arguments for other commands store them in `prefix-arg'.
In contrast, `current-prefix-arg' conveys the prefix argument to the
current command, so setting it has no effect on the prefix arguments
for future commands.

   Normally, commands specify which representation to use for the prefix
argument, either numeric or raw, in the `interactive' specification.
(*Note Using Interactive::.)  Alternatively, functions may look at the
value of the prefix argument directly in the variable
`current-prefix-arg', but this is less clean.

 -- Function: prefix-numeric-value arg
     This function returns the numeric meaning of a valid raw prefix
     argument value, ARG.  The argument may be a symbol, a number, or a
     list.  If it is `nil', the value 1 is returned; if it is `-', the
     value -1 is returned; if it is a number, that number is returned;
     if it is a list, the CAR of that list (which should be a number) is
     returned.

 -- Variable: current-prefix-arg
     This variable holds the raw prefix argument for the _current_
     command.  Commands may examine it directly, but the usual method
     for accessing it is with `(interactive "P")'.

 -- Variable: prefix-arg
     The value of this variable is the raw prefix argument for the
     _next_ editing command.  Commands such as `universal-argument'
     that specify prefix arguments for the following command work by
     setting this variable.

 -- Variable: last-prefix-arg
     The raw prefix argument value used by the previous command.

   The following commands exist to set up prefix arguments for the
following command.  Do not call them for any other reason.

 -- Command: universal-argument
     This command reads input and specifies a prefix argument for the
     following command.  Don't call this command yourself unless you
     know what you are doing.

 -- Command: digit-argument arg
     This command adds to the prefix argument for the following
     command.  The argument ARG is the raw prefix argument as it was
     before this command; it is used to compute the updated prefix
     argument.  Don't call this command yourself unless you know what
     you are doing.

 -- Command: negative-argument arg
     This command adds to the numeric argument for the next command.
     The argument ARG is the raw prefix argument as it was before this
     command; its value is negated to form the new prefix argument.
     Don't call this command yourself unless you know what you are
     doing.


File: elisp,  Node: Recursive Editing,  Next: Disabling Commands,  Prev: Prefix Command Arguments,  Up: Command Loop

21.13 Recursive Editing
=======================

The Emacs command loop is entered automatically when Emacs starts up.
This top-level invocation of the command loop never exits; it keeps
running as long as Emacs does.  Lisp programs can also invoke the
command loop.  Since this makes more than one activation of the command
loop, we call it "recursive editing".  A recursive editing level has
the effect of suspending whatever command invoked it and permitting the
user to do arbitrary editing before resuming that command.

   The commands available during recursive editing are the same ones
available in the top-level editing loop and defined in the keymaps.
Only a few special commands exit the recursive editing level; the others
return to the recursive editing level when they finish.  (The special
commands for exiting are always available, but they do nothing when
recursive editing is not in progress.)

   All command loops, including recursive ones, set up all-purpose error
handlers so that an error in a command run from the command loop will
not exit the loop.

   Minibuffer input is a special kind of recursive editing.  It has a
few special wrinkles, such as enabling display of the minibuffer and the
minibuffer window, but fewer than you might suppose.  Certain keys
behave differently in the minibuffer, but that is only because of the
minibuffer's local map; if you switch windows, you get the usual Emacs
commands.

   To invoke a recursive editing level, call the function
`recursive-edit'.  This function contains the command loop; it also
contains a call to `catch' with tag `exit', which makes it possible to
exit the recursive editing level by throwing to `exit' (*note Catch and
Throw::).  If you throw a value other than `t', then `recursive-edit'
returns normally to the function that called it.  The command `C-M-c'
(`exit-recursive-edit') does this.  Throwing a `t' value causes
`recursive-edit' to quit, so that control returns to the command loop
one level up.  This is called "aborting", and is done by `C-]'
(`abort-recursive-edit').

   Most applications should not use recursive editing, except as part of
using the minibuffer.  Usually it is more convenient for the user if you
change the major mode of the current buffer temporarily to a special
major mode, which should have a command to go back to the previous mode.
(The `e' command in Rmail uses this technique.)  Or, if you wish to
give the user different text to edit "recursively", create and select a
new buffer in a special mode.  In this mode, define a command to
complete the processing and go back to the previous buffer.  (The `m'
command in Rmail does this.)

   Recursive edits are useful in debugging.  You can insert a call to
`debug' into a function definition as a sort of breakpoint, so that you
can look around when the function gets there.  `debug' invokes a
recursive edit but also provides the other features of the debugger.

   Recursive editing levels are also used when you type `C-r' in
`query-replace' or use `C-x q' (`kbd-macro-query').

 -- Command: recursive-edit
     This function invokes the editor command loop.  It is called
     automatically by the initialization of Emacs, to let the user begin
     editing.  When called from a Lisp program, it enters a recursive
     editing level.

     If the current buffer is not the same as the selected window's
     buffer, `recursive-edit' saves and restores the current buffer.
     Otherwise, if you switch buffers, the buffer you switched to is
     current after `recursive-edit' returns.

     In the following example, the function `simple-rec' first advances
     point one word, then enters a recursive edit, printing out a
     message in the echo area.  The user can then do any editing
     desired, and then type `C-M-c' to exit and continue executing
     `simple-rec'.

          (defun simple-rec ()
            (forward-word 1)
            (message "Recursive edit in progress")
            (recursive-edit)
            (forward-word 1))
               => simple-rec
          (simple-rec)
               => nil

 -- Command: exit-recursive-edit
     This function exits from the innermost recursive edit (including
     minibuffer input).  Its definition is effectively `(throw 'exit
     nil)'.

 -- Command: abort-recursive-edit
     This function aborts the command that requested the innermost
     recursive edit (including minibuffer input), by signaling `quit'
     after exiting the recursive edit.  Its definition is effectively
     `(throw 'exit t)'.  *Note Quitting::.

 -- Command: top-level
     This function exits all recursive editing levels; it does not
     return a value, as it jumps completely out of any computation
     directly back to the main command loop.

 -- Function: recursion-depth
     This function returns the current depth of recursive edits.  When
     no recursive edit is active, it returns 0.


File: elisp,  Node: Disabling Commands,  Next: Command History,  Prev: Recursive Editing,  Up: Command Loop

21.14 Disabling Commands
========================

"Disabling a command" marks the command as requiring user confirmation
before it can be executed.  Disabling is used for commands which might
be confusing to beginning users, to prevent them from using the
commands by accident.

   The low-level mechanism for disabling a command is to put a
non-`nil' `disabled' property on the Lisp symbol for the command.
These properties are normally set up by the user's init file (*note
Init File::) with Lisp expressions such as this:

     (put 'upcase-region 'disabled t)

For a few commands, these properties are present by default (you can
remove them in your init file if you wish).

   If the value of the `disabled' property is a string, the message
saying the command is disabled includes that string.  For example:

     (put 'delete-region 'disabled
          "Text deleted this way cannot be yanked back!\n")

   *Note Disabling: (emacs)Disabling, for the details on what happens
when a disabled command is invoked interactively.  Disabling a command
has no effect on calling it as a function from Lisp programs.

 -- Command: enable-command command
     Allow COMMAND (a symbol) to be executed without special
     confirmation from now on, and alter the user's init file (*note
     Init File::) so that this will apply to future sessions.

 -- Command: disable-command command
     Require special confirmation to execute COMMAND from now on, and
     alter the user's init file so that this will apply to future
     sessions.

 -- Variable: disabled-command-function
     The value of this variable should be a function.  When the user
     invokes a disabled command interactively, this function is called
     instead of the disabled command.  It can use `this-command-keys'
     to determine what the user typed to run the command, and thus find
     the command itself.

     The value may also be `nil'.  Then all commands work normally,
     even disabled ones.

     By default, the value is a function that asks the user whether to
     proceed.


File: elisp,  Node: Command History,  Next: Keyboard Macros,  Prev: Disabling Commands,  Up: Command Loop

21.15 Command History
=====================

The command loop keeps a history of the complex commands that have been
executed, to make it convenient to repeat these commands.  A "complex
command" is one for which the interactive argument reading uses the
minibuffer.  This includes any `M-x' command, any `M-:' command, and
any command whose `interactive' specification reads an argument from
the minibuffer.  Explicit use of the minibuffer during the execution of
the command itself does not cause the command to be considered complex.

 -- Variable: command-history
     This variable's value is a list of recent complex commands, each
     represented as a form to evaluate.  It continues to accumulate all
     complex commands for the duration of the editing session, but when
     it reaches the maximum size (*note Minibuffer History::), the
     oldest elements are deleted as new ones are added.

          command-history
          => ((switch-to-buffer "chistory.texi")
              (describe-key "^X^[")
              (visit-tags-table "~/emacs/src/")
              (find-tag "repeat-complex-command"))

   This history list is actually a special case of minibuffer history
(*note Minibuffer History::), with one special twist: the elements are
expressions rather than strings.

   There are a number of commands devoted to the editing and recall of
previous commands.  The commands `repeat-complex-command', and
`list-command-history' are described in the user manual (*note
Repetition: (emacs)Repetition.).  Within the minibuffer, the usual
minibuffer history commands are available.


File: elisp,  Node: Keyboard Macros,  Prev: Command History,  Up: Command Loop

21.16 Keyboard Macros
=====================

A "keyboard macro" is a canned sequence of input events that can be
considered a command and made the definition of a key.  The Lisp
representation of a keyboard macro is a string or vector containing the
events.  Don't confuse keyboard macros with Lisp macros (*note
Macros::).

 -- Function: execute-kbd-macro kbdmacro &optional count loopfunc
     This function executes KBDMACRO as a sequence of events.  If
     KBDMACRO is a string or vector, then the events in it are executed
     exactly as if they had been input by the user.  The sequence is
     _not_ expected to be a single key sequence; normally a keyboard
     macro definition consists of several key sequences concatenated.

     If KBDMACRO is a symbol, then its function definition is used in
     place of KBDMACRO.  If that is another symbol, this process
     repeats.  Eventually the result should be a string or vector.  If
     the result is not a symbol, string, or vector, an error is
     signaled.

     The argument COUNT is a repeat count; KBDMACRO is executed that
     many times.  If COUNT is omitted or `nil', KBDMACRO is executed
     once.  If it is 0, KBDMACRO is executed over and over until it
     encounters an error or a failing search.

     If LOOPFUNC is non-`nil', it is a function that is called, without
     arguments, prior to each iteration of the macro.  If LOOPFUNC
     returns `nil', then this stops execution of the macro.

     *Note Reading One Event::, for an example of using
     `execute-kbd-macro'.

 -- Variable: executing-kbd-macro
     This variable contains the string or vector that defines the
     keyboard macro that is currently executing.  It is `nil' if no
     macro is currently executing.  A command can test this variable so
     as to behave differently when run from an executing macro.  Do not
     set this variable yourself.

 -- Variable: defining-kbd-macro
     This variable is non-`nil' if and only if a keyboard macro is
     being defined.  A command can test this variable so as to behave
     differently while a macro is being defined.  The value is `append'
     while appending to the definition of an existing macro.  The
     commands `start-kbd-macro', `kmacro-start-macro' and
     `end-kbd-macro' set this variable--do not set it yourself.

     The variable is always local to the current terminal and cannot be
     buffer-local.  *Note Multiple Terminals::.

 -- Variable: last-kbd-macro
     This variable is the definition of the most recently defined
     keyboard macro.  Its value is a string or vector, or `nil'.

     The variable is always local to the current terminal and cannot be
     buffer-local.  *Note Multiple Terminals::.

 -- Variable: kbd-macro-termination-hook
     This normal hook is run when a keyboard macro terminates,
     regardless of what caused it to terminate (reaching the macro end
     or an error which ended the macro prematurely).


File: elisp,  Node: Keymaps,  Next: Modes,  Prev: Command Loop,  Up: Top

22 Keymaps
**********

The command bindings of input events are recorded in data structures
called "keymaps".  Each entry in a keymap associates (or "binds") an
individual event type, either to another keymap or to a command.  When
an event type is bound to a keymap, that keymap is used to look up the
next input event; this continues until a command is found.  The whole
process is called "key lookup".

* Menu:

* Key Sequences::               Key sequences as Lisp objects.
* Keymap Basics::               Basic concepts of keymaps.
* Format of Keymaps::           What a keymap looks like as a Lisp object.
* Creating Keymaps::            Functions to create and copy keymaps.
* Inheritance and Keymaps::     How one keymap can inherit the bindings
                                   of another keymap.
* Prefix Keys::                 Defining a key with a keymap as its definition.
* Active Keymaps::              How Emacs searches the active keymaps
                                   for a key binding.
* Searching Keymaps::           A pseudo-Lisp summary of searching active maps.
* Controlling Active Maps::     Each buffer has a local keymap
                                   to override the standard (global) bindings.
                                   A minor mode can also override them.
* Key Lookup::                  Finding a key's binding in one keymap.
* Functions for Key Lookup::    How to request key lookup.
* Changing Key Bindings::       Redefining a key in a keymap.
* Remapping Commands::          A keymap can translate one command to another.
* Translation Keymaps::         Keymaps for translating sequences of events.
* Key Binding Commands::        Interactive interfaces for redefining keys.
* Scanning Keymaps::            Looking through all keymaps, for printing help.
* Menu Keymaps::                Defining a menu as a keymap.


File: elisp,  Node: Key Sequences,  Next: Keymap Basics,  Up: Keymaps

22.1 Key Sequences
==================

A "key sequence", or "key" for short, is a sequence of one or more
input events that form a unit.  Input events include characters,
function keys, and mouse actions (*note Input Events::).  The Emacs
Lisp representation for a key sequence is a string or vector.  Unless
otherwise stated, any Emacs Lisp function that accepts a key sequence
as an argument can handle both representations.

   In the string representation, alphanumeric characters ordinarily
stand for themselves; for example, `"a"' represents `a' and `"2"'
represents `2'.  Control character events are prefixed by the substring
`"\C-"', and meta characters by `"\M-"'; for example, `"\C-x"'
represents the key `C-x'.  In addition, the <TAB>, <RET>, <ESC>, and
<DEL> events are represented by `"\t"', `"\r"', `"\e"', and `"\d"'
respectively.  The string representation of a complete key sequence is
the concatenation of the string representations of the constituent
events; thus, `"\C-xl"' represents the key sequence `C-x l'.

   Key sequences containing function keys, mouse button events, or
non-ASCII characters such as `C-=' or `H-a' cannot be represented as
strings; they have to be represented as vectors.

   In the vector representation, each element of the vector represents
an input event, in its Lisp form.  *Note Input Events::.  For example,
the vector `[?\C-x ?l]' represents the key sequence `C-x l'.

   For examples of key sequences written in string and vector
representations, *note Init Rebinding: (emacs)Init Rebinding.

 -- Macro: kbd keyseq-text
     This macro converts the text KEYSEQ-TEXT (a string constant) into
     a key sequence (a string or vector constant).  The contents of
     KEYSEQ-TEXT should describe the key sequence using almost the same
     syntax used in this manual.  More precisely, it uses the same
     syntax that Edit Macro mode uses for editing keyboard macros
     (*note Edit Keyboard Macro: (emacs)Edit Keyboard Macro.); you must
     surround function key names with `<...>'.

          (kbd "C-x") => "\C-x"
          (kbd "C-x C-f") => "\C-x\C-f"
          (kbd "C-x 4 C-f") => "\C-x4\C-f"
          (kbd "X") => "X"
          (kbd "RET") => "\^M"
          (kbd "C-c SPC") => "\C-c "
          (kbd "<f1> SPC") => [f1 32]
          (kbd "C-M-<down>") => [C-M-down]

     This macro is not meant for use with arguments that vary--only
     with string constants.


File: elisp,  Node: Keymap Basics,  Next: Format of Keymaps,  Prev: Key Sequences,  Up: Keymaps

22.2 Keymap Basics
==================

A keymap is a Lisp data structure that specifies "key bindings" for
various key sequences.

   A single keymap directly specifies definitions for individual
events.  When a key sequence consists of a single event, its binding in
a keymap is the keymap's definition for that event.  The binding of a
longer key sequence is found by an iterative process: first find the
definition of the first event (which must itself be a keymap); then
find the second event's definition in that keymap, and so on until all
the events in the key sequence have been processed.

   If the binding of a key sequence is a keymap, we call the key
sequence a "prefix key".  Otherwise, we call it a "complete key"
(because no more events can be added to it).  If the binding is `nil',
we call the key "undefined".  Examples of prefix keys are `C-c', `C-x',
and `C-x 4'.  Examples of defined complete keys are `X', <RET>, and
`C-x 4 C-f'.  Examples of undefined complete keys are `C-x C-g', and
`C-c 3'.  *Note Prefix Keys::, for more details.

   The rule for finding the binding of a key sequence assumes that the
intermediate bindings (found for the events before the last) are all
keymaps; if this is not so, the sequence of events does not form a
unit--it is not really one key sequence.  In other words, removing one
or more events from the end of any valid key sequence must always yield
a prefix key.  For example, `C-f C-n' is not a key sequence; `C-f' is
not a prefix key, so a longer sequence starting with `C-f' cannot be a
key sequence.

   The set of possible multi-event key sequences depends on the bindings
for prefix keys; therefore, it can be different for different keymaps,
and can change when bindings are changed.  However, a one-event sequence
is always a key sequence, because it does not depend on any prefix keys
for its well-formedness.

   At any time, several primary keymaps are "active"--that is, in use
for finding key bindings.  These are the "global map", which is shared
by all buffers; the "local keymap", which is usually associated with a
specific major mode; and zero or more "minor mode keymaps", which
belong to currently enabled minor modes.  (Not all minor modes have
keymaps.)  The local keymap bindings shadow (i.e., take precedence
over) the corresponding global bindings.  The minor mode keymaps shadow
both local and global keymaps.  *Note Active Keymaps::, for details.


File: elisp,  Node: Format of Keymaps,  Next: Creating Keymaps,  Prev: Keymap Basics,  Up: Keymaps

22.3 Format of Keymaps
======================

Each keymap is a list whose CAR is the symbol `keymap'.  The remaining
elements of the list define the key bindings of the keymap.  A symbol
whose function definition is a keymap is also a keymap.  Use the
function `keymapp' (see below) to test whether an object is a keymap.

   Several kinds of elements may appear in a keymap, after the symbol
`keymap' that begins it:

`(TYPE . BINDING)'
     This specifies one binding, for events of type TYPE.  Each
     ordinary binding applies to events of a particular "event type",
     which is always a character or a symbol.  *Note Classifying
     Events::.  In this kind of binding, BINDING is a command.

`(TYPE ITEM-NAME . BINDING)'
     This specifies a binding which is also a simple menu item that
     displays as ITEM-NAME in the menu.  *Note Simple Menu Items::.

`(TYPE ITEM-NAME HELP-STRING . BINDING)'
     This is a simple menu item with help string HELP-STRING.

`(TYPE menu-item . DETAILS)'
     This specifies a binding which is also an extended menu item.  This
     allows use of other features.  *Note Extended Menu Items::.

`(t . BINDING)'
     This specifies a "default key binding"; any event not bound by
     other elements of the keymap is given BINDING as its binding.
     Default bindings allow a keymap to bind all possible event types
     without having to enumerate all of them.  A keymap that has a
     default binding completely masks any lower-precedence keymap,
     except for events explicitly bound to `nil' (see below).

`CHAR-TABLE'
     If an element of a keymap is a char-table, it counts as holding
     bindings for all character events with no modifier bits (*note
     modifier bits::): element N is the binding for the character with
     code N.  This is a compact way to record lots of bindings.  A
     keymap with such a char-table is called a "full keymap".  Other
     keymaps are called "sparse keymaps".

`STRING'
     Aside from elements that specify bindings for keys, a keymap can
     also have a string as an element.  This is called the "overall
     prompt string" and makes it possible to use the keymap as a menu.
     *Note Defining Menus::.

   When the binding is `nil', it doesn't constitute a definition but it
does take precedence over a default binding or a binding in the parent
keymap.  On the other hand, a binding of `nil' does _not_ override
lower-precedence keymaps; thus, if the local map gives a binding of
`nil', Emacs uses the binding from the global map.

   Keymaps do not directly record bindings for the meta characters.
Instead, meta characters are regarded for purposes of key lookup as
sequences of two characters, the first of which is <ESC> (or whatever
is currently the value of `meta-prefix-char').  Thus, the key `M-a' is
internally represented as `<ESC> a', and its global binding is found at
the slot for `a' in `esc-map' (*note Prefix Keys::).

   This conversion applies only to characters, not to function keys or
other input events; thus, `M-<end>' has nothing to do with `<ESC>
<end>'.

   Here as an example is the local keymap for Lisp mode, a sparse
keymap.  It defines bindings for <DEL>, `C-c C-z', `C-M-q', and `C-M-x'
(the actual value also contains a menu binding, which is omitted here
for the sake of brevity).

     lisp-mode-map
     =>
     (keymap
      (3 keymap
         ;; C-c C-z
         (26 . run-lisp))
      (27 keymap
          ;; `C-M-x', treated as `<ESC> C-x'
          (24 . lisp-send-defun))
      ;; This part is inherited from `lisp-mode-shared-map'.
      keymap
      ;; <DEL>
      (127 . backward-delete-char-untabify)
      (27 keymap
          ;; `C-M-q', treated as `<ESC> C-q'
          (17 . indent-sexp)))

 -- Function: keymapp object
     This function returns `t' if OBJECT is a keymap, `nil' otherwise.
     More precisely, this function tests for a list whose CAR is
     `keymap', or for a symbol whose function definition satisfies
     `keymapp'.

          (keymapp '(keymap))
              => t
          (fset 'foo '(keymap))
          (keymapp 'foo)
              => t
          (keymapp (current-global-map))
              => t


File: elisp,  Node: Creating Keymaps,  Next: Inheritance and Keymaps,  Prev: Format of Keymaps,  Up: Keymaps

22.4 Creating Keymaps
=====================

Here we describe the functions for creating keymaps.

 -- Function: make-sparse-keymap &optional prompt
     This function creates and returns a new sparse keymap with no
     entries.  (A sparse keymap is the kind of keymap you usually
     want.)  The new keymap does not contain a char-table, unlike
     `make-keymap', and does not bind any events.

          (make-sparse-keymap)
              => (keymap)

     If you specify PROMPT, that becomes the overall prompt string for
     the keymap.  You should specify this only for menu keymaps (*note
     Defining Menus::).  A keymap with an overall prompt string will
     always present a mouse menu or a keyboard menu if it is active for
     looking up the next input event.  Don't specify an overall prompt
     string for the main map of a major or minor mode, because that
     would cause the command loop to present a keyboard menu every time.

 -- Function: make-keymap &optional prompt
     This function creates and returns a new full keymap.  That keymap
     contains a char-table (*note Char-Tables::) with slots for all
     characters without modifiers.  The new keymap initially binds all
     these characters to `nil', and does not bind any other kind of
     event.  The argument PROMPT specifies a prompt string, as in
     `make-sparse-keymap'.

          (make-keymap)
              => (keymap #^[t nil nil nil ... nil nil keymap])

     A full keymap is more efficient than a sparse keymap when it holds
     lots of bindings; for just a few, the sparse keymap is better.

 -- Function: copy-keymap keymap
     This function returns a copy of KEYMAP.  Any keymaps that appear
     directly as bindings in KEYMAP are also copied recursively, and so
     on to any number of levels.  However, recursive copying does not
     take place when the definition of a character is a symbol whose
     function definition is a keymap; the same symbol appears in the
     new copy.

          (setq map (copy-keymap (current-local-map)))
          => (keymap
               ;; (This implements meta characters.)
               (27 keymap
                   (83 . center-paragraph)
                   (115 . center-line))
               (9 . tab-to-tab-stop))

          (eq map (current-local-map))
              => nil
          (equal map (current-local-map))
              => t


File: elisp,  Node: Inheritance and Keymaps,  Next: Prefix Keys,  Prev: Creating Keymaps,  Up: Keymaps

22.5 Inheritance and Keymaps
============================

A keymap can inherit the bindings of another keymap, which we call the
"parent keymap".  Such a keymap looks like this:

     (keymap ELEMENTS... . PARENT-KEYMAP)

The effect is that this keymap inherits all the bindings of
PARENT-KEYMAP, whatever they may be at the time a key is looked up, but
can add to them or override them with ELEMENTS.

   If you change the bindings in PARENT-KEYMAP using `define-key' or
other key-binding functions, these changed bindings are visible in the
inheriting keymap, unless shadowed by the bindings made by ELEMENTS.
The converse is not true: if you use `define-key' to change bindings in
the inheriting keymap, these changes are recorded in ELEMENTS, but have
no effect on PARENT-KEYMAP.

   The proper way to construct a keymap with a parent is to use
`set-keymap-parent'; if you have code that directly constructs a keymap
with a parent, please convert the program to use `set-keymap-parent'
instead.

 -- Function: keymap-parent keymap
     This returns the parent keymap of KEYMAP.  If KEYMAP has no
     parent, `keymap-parent' returns `nil'.

 -- Function: set-keymap-parent keymap parent
     This sets the parent keymap of KEYMAP to PARENT, and returns
     PARENT.  If PARENT is `nil', this function gives KEYMAP no parent
     at all.

     If KEYMAP has submaps (bindings for prefix keys), they too receive
     new parent keymaps that reflect what PARENT specifies for those
     prefix keys.

   Here is an example showing how to make a keymap that inherits from
`text-mode-map':

     (let ((map (make-sparse-keymap)))
       (set-keymap-parent map text-mode-map)
       map)

   A non-sparse keymap can have a parent too, but this is not very
useful.  A non-sparse keymap always specifies something as the binding
for every numeric character code without modifier bits, even if it is
`nil', so these character's bindings are never inherited from the
parent keymap.

   Sometimes you want to make a keymap that inherits from more than one
map.  You can use the function `make-composed-keymap' for this.

 -- Function: make-composed-keymap maps &optional parent
     This function returns a new keymap composed of the existing
     keymap(s) MAPS, and optionally inheriting from a parent keymap
     PARENT.  MAPS can be a single keymap or a list of more than one.
     When looking up a key in the resulting new map, Emacs searches in
     each of the MAPS in turn, and then in PARENT, stopping at the
     first match.  A `nil' binding in any one of MAPS overrides any
     binding in PARENT, but it does not override any non-`nil' binding
     in any other of the MAPS.

For example, here is how Emacs sets the parent of `help-mode-map', such
that it inherits from both `button-buffer-map' and `special-mode-map':

     (defvar help-mode-map
       (let ((map (make-sparse-keymap)))
         (set-keymap-parent map
           (make-composed-keymap button-buffer-map special-mode-map))
         ... map) ... )


File: elisp,  Node: Prefix Keys,  Next: Active Keymaps,  Prev: Inheritance and Keymaps,  Up: Keymaps

22.6 Prefix Keys
================

A "prefix key" is a key sequence whose binding is a keymap.  The keymap
defines what to do with key sequences that extend the prefix key.  For
example, `C-x' is a prefix key, and it uses a keymap that is also
stored in the variable `ctl-x-map'.  This keymap defines bindings for
key sequences starting with `C-x'.

   Some of the standard Emacs prefix keys use keymaps that are also
found in Lisp variables:

   * `esc-map' is the global keymap for the <ESC> prefix key.  Thus,
     the global definitions of all meta characters are actually found
     here.  This map is also the function definition of `ESC-prefix'.

   * `help-map' is the global keymap for the `C-h' prefix key.

   * `mode-specific-map' is the global keymap for the prefix key `C-c'.
     This map is actually global, not mode-specific, but its name
     provides useful information about `C-c' in the output of `C-h b'
     (`display-bindings'), since the main use of this prefix key is for
     mode-specific bindings.

   * `ctl-x-map' is the global keymap used for the `C-x' prefix key.
     This map is found via the function cell of the symbol
     `Control-X-prefix'.

   * `mule-keymap' is the global keymap used for the `C-x <RET>' prefix
     key.

   * `ctl-x-4-map' is the global keymap used for the `C-x 4' prefix key.

   * `ctl-x-5-map' is the global keymap used for the `C-x 5' prefix key.

   * `2C-mode-map' is the global keymap used for the `C-x 6' prefix key.

   * `vc-prefix-map' is the global keymap used for the `C-x v' prefix
     key.

   * `goto-map' is the global keymap used for the `M-g' prefix key.

   * `search-map' is the global keymap used for the `M-s' prefix key.

   * `facemenu-keymap' is the global keymap used for the `M-o' prefix
     key.

   * The other Emacs prefix keys are `C-x @', `C-x a i', `C-x <ESC>'
     and `<ESC> <ESC>'.  They use keymaps that have no special names.

   The keymap binding of a prefix key is used for looking up the event
that follows the prefix key.  (It may instead be a symbol whose function
definition is a keymap.  The effect is the same, but the symbol serves
as a name for the prefix key.)  Thus, the binding of `C-x' is the
symbol `Control-X-prefix', whose function cell holds the keymap for
`C-x' commands.  (The same keymap is also the value of `ctl-x-map'.)

   Prefix key definitions can appear in any active keymap.  The
definitions of `C-c', `C-x', `C-h' and <ESC> as prefix keys appear in
the global map, so these prefix keys are always available.  Major and
minor modes can redefine a key as a prefix by putting a prefix key
definition for it in the local map or the minor mode's map.  *Note
Active Keymaps::.

   If a key is defined as a prefix in more than one active map, then its
various definitions are in effect merged: the commands defined in the
minor mode keymaps come first, followed by those in the local map's
prefix definition, and then by those from the global map.

   In the following example, we make `C-p' a prefix key in the local
keymap, in such a way that `C-p' is identical to `C-x'.  Then the
binding for `C-p C-f' is the function `find-file', just like `C-x C-f'.
The key sequence `C-p 6' is not found in any active keymap.

     (use-local-map (make-sparse-keymap))
         => nil
     (local-set-key "\C-p" ctl-x-map)
         => nil
     (key-binding "\C-p\C-f")
         => find-file

     (key-binding "\C-p6")
         => nil

 -- Function: define-prefix-command symbol &optional mapvar prompt
     This function prepares SYMBOL for use as a prefix key's binding:
     it creates a sparse keymap and stores it as SYMBOL's function
     definition.  Subsequently binding a key sequence to SYMBOL will
     make that key sequence into a prefix key.  The return value is
     `symbol'.

     This function also sets SYMBOL as a variable, with the keymap as
     its value.  But if MAPVAR is non-`nil', it sets MAPVAR as a
     variable instead.

     If PROMPT is non-`nil', that becomes the overall prompt string for
     the keymap.  The prompt string should be given for menu keymaps
     (*note Defining Menus::).


File: elisp,  Node: Active Keymaps,  Next: Searching Keymaps,  Prev: Prefix Keys,  Up: Keymaps

22.7 Active Keymaps
===================

Emacs normally contains many keymaps; at any given time, just a few of
them are "active", meaning that they participate in the interpretation
of user input.  All the active keymaps are used together to determine
what command to execute when a key is entered.

   Normally the active keymaps are the `keymap' property keymap, the
keymaps of any enabled minor modes, the current buffer's local keymap,
and the global keymap, in that order.  Emacs searches for each input
key sequence in all these keymaps.  *Note Searching Keymaps::, for more
details of this procedure.

   When the key sequence starts with a mouse event (optionally preceded
by a symbolic prefix), the active keymaps are determined based on the
position in that event.  If the event happened on a string embedded
with a `display', `before-string', or `after-string' property (*note
Special Properties::), the non-`nil' map properties of the string
override those of the buffer (if the underlying buffer text contains
map properties in its text properties or overlays, they are ignored).

   The "global keymap" holds the bindings of keys that are defined
regardless of the current buffer, such as `C-f'.  The variable
`global-map' holds this keymap, which is always active.

   Each buffer may have another keymap, its "local keymap", which may
contain new or overriding definitions for keys.  The current buffer's
local keymap is always active except when `overriding-local-map'
overrides it.  The `local-map' text or overlay property can specify an
alternative local keymap for certain parts of the buffer; see *note
Special Properties::.

   Each minor mode can have a keymap; if it does, the keymap is active
when the minor mode is enabled.  Modes for emulation can specify
additional active keymaps through the variable
`emulation-mode-map-alists'.

   The highest precedence normal keymap comes from the `keymap' text or
overlay property.  If that is non-`nil', it is the first keymap to be
processed, in normal circumstances.

   However, there are also special ways for programs to substitute
other keymaps for some of those.  The variable `overriding-local-map',
if non-`nil', specifies a keymap that replaces all the usual active
keymaps except the global keymap.  Another way to do this is with
`overriding-terminal-local-map'; it operates on a per-terminal basis.
These variables are documented below.

   Since every buffer that uses the same major mode normally uses the
same local keymap, you can think of the keymap as local to the mode.  A
change to the local keymap of a buffer (using `local-set-key', for
example) is seen also in the other buffers that share that keymap.

   The local keymaps that are used for Lisp mode and some other major
modes exist even if they have not yet been used.  These local keymaps
are the values of variables such as `lisp-mode-map'.  For most major
modes, which are less frequently used, the local keymap is constructed
only when the mode is used for the first time in a session.

   The minibuffer has local keymaps, too; they contain various
completion and exit commands.  *Note Intro to Minibuffers::.

   Emacs has other keymaps that are used in a different way--translating
events within `read-key-sequence'.  *Note Translation Keymaps::.

   *Note Standard Keymaps::, for a list of some standard keymaps.

 -- Function: current-active-maps &optional olp position
     This returns the list of active keymaps that would be used by the
     command loop in the current circumstances to look up a key
     sequence.  Normally it ignores `overriding-local-map' and
     `overriding-terminal-local-map', but if OLP is non-`nil' then it
     pays attention to them.  POSITION can optionally be either an
     event position as returned by `event-start' or a buffer position,
     and may change the keymaps as described for `key-binding'.

 -- Function: key-binding key &optional accept-defaults no-remap
          position
     This function returns the binding for KEY according to the current
     active keymaps.  The result is `nil' if KEY is undefined in the
     keymaps.

     The argument ACCEPT-DEFAULTS controls checking for default
     bindings, as in `lookup-key' (*note Functions for Key Lookup::).

     When commands are remapped (*note Remapping Commands::),
     `key-binding' normally processes command remappings so as to
     return the remapped command that will actually be executed.
     However, if NO-REMAP is non-`nil', `key-binding' ignores
     remappings and returns the binding directly specified for KEY.

     If KEY starts with a mouse event (perhaps following a prefix
     event), the maps to be consulted are determined based on the
     event's position.  Otherwise, they are determined based on the
     value of point.  However, you can override either of them by
     specifying POSITION.  If POSITION is non-`nil', it should be
     either a buffer position or an event position like the value of
     `event-start'.  Then the maps consulted are determined based on
     POSITION.

     An error is signaled if KEY is not a string or a vector.

          (key-binding "\C-x\C-f")
              => find-file


File: elisp,  Node: Searching Keymaps,  Next: Controlling Active Maps,  Prev: Active Keymaps,  Up: Keymaps

22.8 Searching the Active Keymaps
=================================

After translation of event subsequences (*note Translation Keymaps::)
Emacs looks for them in the active keymaps.  Here is a pseudo-Lisp
description of the order and conditions for searching them:

     (or (cond
          (overriding-terminal-local-map
           (FIND-IN overriding-terminal-local-map))
          (overriding-local-map
           (FIND-IN overriding-local-map))
          ((or (FIND-IN (get-char-property (point) 'keymap))
     	  (FIND-IN-ANY emulation-mode-map-alists)
     	  (FIND-IN-ANY minor-mode-overriding-map-alist)
     	  (FIND-IN-ANY minor-mode-map-alist)
     	  (if (get-text-property (point) 'local-map)
     	      (FIND-IN (get-char-property (point) 'local-map))
     	    (FIND-IN (current-local-map))))))
         (FIND-IN (current-global-map)))

FIND-IN and FIND-IN-ANY are pseudo functions that search in one keymap
and in an alist of keymaps, respectively.  (Searching a single keymap
for a binding is called "key lookup"; see *note Key Lookup::.)  If the
key sequence starts with a mouse event, or a symbolic prefix event
followed by a mouse event, that event's position is used instead of
point and the current buffer.  Mouse events on an embedded string use
non-`nil' text properties from that string instead of the buffer.

   When a match is found (*note Key Lookup::), if the binding in the
keymap is a function, the search is over.  However if the keymap entry
is a symbol with a value or a string, Emacs replaces the input key
sequences with the variable's value or the string, and restarts the
search of the active keymaps.

   The function finally found might also be remapped.  *Note Remapping
Commands::.


File: elisp,  Node: Controlling Active Maps,  Next: Key Lookup,  Prev: Searching Keymaps,  Up: Keymaps

22.9 Controlling the Active Keymaps
===================================

 -- Variable: global-map
     This variable contains the default global keymap that maps Emacs
     keyboard input to commands.  The global keymap is normally this
     keymap.  The default global keymap is a full keymap that binds
     `self-insert-command' to all of the printing characters.

     It is normal practice to change the bindings in the global keymap,
     but you should not assign this variable any value other than the
     keymap it starts out with.

 -- Function: current-global-map
     This function returns the current global keymap.  This is the same
     as the value of `global-map' unless you change one or the other.
     The return value is a reference, not a copy; if you use
     `define-key' or other functions on it you will alter global
     bindings.

          (current-global-map)
          => (keymap [set-mark-command beginning-of-line ...
                      delete-backward-char])

 -- Function: current-local-map
     This function returns the current buffer's local keymap, or `nil'
     if it has none.  In the following example, the keymap for the
     `*scratch*' buffer (using Lisp Interaction mode) is a sparse keymap
     in which the entry for <ESC>, ASCII code 27, is another sparse
     keymap.

          (current-local-map)
          => (keymap
              (10 . eval-print-last-sexp)
              (9 . lisp-indent-line)
              (127 . backward-delete-char-untabify)
              (27 keymap
                  (24 . eval-defun)
                  (17 . indent-sexp)))

   `current-local-map' returns a reference to the local keymap, not a
copy of it; if you use `define-key' or other functions on it you will
alter local bindings.

 -- Function: current-minor-mode-maps
     This function returns a list of the keymaps of currently enabled
     minor modes.

 -- Function: use-global-map keymap
     This function makes KEYMAP the new current global keymap.  It
     returns `nil'.

     It is very unusual to change the global keymap.

 -- Function: use-local-map keymap
     This function makes KEYMAP the new local keymap of the current
     buffer.  If KEYMAP is `nil', then the buffer has no local keymap.
     `use-local-map' returns `nil'.  Most major mode commands use this
     function.

 -- Variable: minor-mode-map-alist
     This variable is an alist describing keymaps that may or may not be
     active according to the values of certain variables.  Its elements
     look like this:

          (VARIABLE . KEYMAP)

     The keymap KEYMAP is active whenever VARIABLE has a non-`nil'
     value.  Typically VARIABLE is the variable that enables or
     disables a minor mode.  *Note Keymaps and Minor Modes::.

     Note that elements of `minor-mode-map-alist' do not have the same
     structure as elements of `minor-mode-alist'.  The map must be the
     CDR of the element; a list with the map as the second element will
     not do.  The CDR can be either a keymap (a list) or a symbol whose
     function definition is a keymap.

     When more than one minor mode keymap is active, the earlier one in
     `minor-mode-map-alist' takes priority.  But you should design
     minor modes so that they don't interfere with each other.  If you
     do this properly, the order will not matter.

     See *note Keymaps and Minor Modes::, for more information about
     minor modes.  See also `minor-mode-key-binding' (*note Functions
     for Key Lookup::).

 -- Variable: minor-mode-overriding-map-alist
     This variable allows major modes to override the key bindings for
     particular minor modes.  The elements of this alist look like the
     elements of `minor-mode-map-alist': `(VARIABLE . KEYMAP)'.

     If a variable appears as an element of
     `minor-mode-overriding-map-alist', the map specified by that
     element totally replaces any map specified for the same variable in
     `minor-mode-map-alist'.

     `minor-mode-overriding-map-alist' is automatically buffer-local in
     all buffers.

 -- Variable: overriding-local-map
     If non-`nil', this variable holds a keymap to use instead of the
     buffer's local keymap, any text property or overlay keymaps, and
     any minor mode keymaps.  This keymap, if specified, overrides all
     other maps that would have been active, except for the current
     global map.

 -- Variable: overriding-terminal-local-map
     If non-`nil', this variable holds a keymap to use instead of
     `overriding-local-map', the buffer's local keymap, text property
     or overlay keymaps, and all the minor mode keymaps.

     This variable is always local to the current terminal and cannot be
     buffer-local.  *Note Multiple Terminals::.  It is used to implement
     incremental search mode.

 -- Variable: overriding-local-map-menu-flag
     If this variable is non-`nil', the value of `overriding-local-map'
     or `overriding-terminal-local-map' can affect the display of the
     menu bar.  The default value is `nil', so those map variables have
     no effect on the menu bar.

     Note that these two map variables do affect the execution of key
     sequences entered using the menu bar, even if they do not affect
     the menu bar display.  So if a menu bar key sequence comes in, you
     should clear the variables before looking up and executing that
     key sequence.  Modes that use the variables would typically do
     this anyway; normally they respond to events that they do not
     handle by "unreading" them and exiting.

 -- Variable: special-event-map
     This variable holds a keymap for special events.  If an event type
     has a binding in this keymap, then it is special, and the binding
     for the event is run directly by `read-event'.  *Note Special
     Events::.

 -- Variable: emulation-mode-map-alists
     This variable holds a list of keymap alists to use for emulations
     modes.  It is intended for modes or packages using multiple
     minor-mode keymaps.  Each element is a keymap alist which has the
     same format and meaning as `minor-mode-map-alist', or a symbol
     with a variable binding which is such an alist.  The "active"
     keymaps in each alist are used before `minor-mode-map-alist' and
     `minor-mode-overriding-map-alist'.


File: elisp,  Node: Key Lookup,  Next: Functions for Key Lookup,  Prev: Controlling Active Maps,  Up: Keymaps

22.10 Key Lookup
================

"Key lookup" is the process of finding the binding of a key sequence
from a given keymap.  The execution or use of the binding is not part
of key lookup.

   Key lookup uses just the event type of each event in the key
sequence; the rest of the event is ignored.  In fact, a key sequence
used for key lookup may designate a mouse event with just its types (a
symbol) instead of the entire event (a list).  *Note Input Events::.
Such a "key sequence" is insufficient for `command-execute' to run, but
it is sufficient for looking up or rebinding a key.

   When the key sequence consists of multiple events, key lookup
processes the events sequentially: the binding of the first event is
found, and must be a keymap; then the second event's binding is found in
that keymap, and so on until all the events in the key sequence are used
up.  (The binding thus found for the last event may or may not be a
keymap.)  Thus, the process of key lookup is defined in terms of a
simpler process for looking up a single event in a keymap.  How that is
done depends on the type of object associated with the event in that
keymap.

   Let's use the term "keymap entry" to describe the value found by
looking up an event type in a keymap.  (This doesn't include the item
string and other extra elements in a keymap element for a menu item,
because `lookup-key' and other key lookup functions don't include them
in the returned value.)  While any Lisp object may be stored in a keymap
as a keymap entry, not all make sense for key lookup.  Here is a table
of the meaningful types of keymap entries:

`nil'
     `nil' means that the events used so far in the lookup form an
     undefined key.  When a keymap fails to mention an event type at
     all, and has no default binding, that is equivalent to a binding
     of `nil' for that event type.

COMMAND
     The events used so far in the lookup form a complete key, and
     COMMAND is its binding.  *Note What Is a Function::.

ARRAY
     The array (either a string or a vector) is a keyboard macro.  The
     events used so far in the lookup form a complete key, and the
     array is its binding.  See *note Keyboard Macros::, for more
     information.

KEYMAP
     The events used so far in the lookup form a prefix key.  The next
     event of the key sequence is looked up in KEYMAP.

LIST
     The meaning of a list depends on what it contains:

        * If the CAR of LIST is the symbol `keymap', then the list is a
          keymap, and is treated as a keymap (see above).

        * If the CAR of LIST is `lambda', then the list is a lambda
          expression.  This is presumed to be a function, and is treated
          as such (see above).  In order to execute properly as a key
          binding, this function must be a command--it must have an
          `interactive' specification.  *Note Defining Commands::.

        * If the CAR of LIST is a keymap and the CDR is an event type,
          then this is an "indirect entry":

               (OTHERMAP . OTHERTYPE)

          When key lookup encounters an indirect entry, it looks up
          instead the binding of OTHERTYPE in OTHERMAP and uses that.

          This feature permits you to define one key as an alias for
          another key.  For example, an entry whose CAR is the keymap
          called `esc-map' and whose CDR is 32 (the code for <SPC>)
          means, "Use the global binding of `Meta-<SPC>', whatever that
          may be".

SYMBOL
     The function definition of SYMBOL is used in place of SYMBOL.  If
     that too is a symbol, then this process is repeated, any number of
     times.  Ultimately this should lead to an object that is a keymap,
     a command, or a keyboard macro.  A list is allowed if it is a
     keymap or a command, but indirect entries are not understood when
     found via symbols.

     Note that keymaps and keyboard macros (strings and vectors) are not
     valid functions, so a symbol with a keymap, string, or vector as
     its function definition is invalid as a function.  It is, however,
     valid as a key binding.  If the definition is a keyboard macro,
     then the symbol is also valid as an argument to `command-execute'
     (*note Interactive Call::).

     The symbol `undefined' is worth special mention: it means to treat
     the key as undefined.  Strictly speaking, the key is defined, and
     its binding is the command `undefined'; but that command does the
     same thing that is done automatically for an undefined key: it
     rings the bell (by calling `ding') but does not signal an error.

     `undefined' is used in local keymaps to override a global key
     binding and make the key "undefined" locally.  A local binding of
     `nil' would fail to do this because it would not override the
     global binding.

ANYTHING ELSE
     If any other type of object is found, the events used so far in the
     lookup form a complete key, and the object is its binding, but the
     binding is not executable as a command.

   In short, a keymap entry may be a keymap, a command, a keyboard
macro, a symbol that leads to one of them, or an indirection or `nil'.


File: elisp,  Node: Functions for Key Lookup,  Next: Changing Key Bindings,  Prev: Key Lookup,  Up: Keymaps

22.11 Functions for Key Lookup
==============================

Here are the functions and variables pertaining to key lookup.

 -- Function: lookup-key keymap key &optional accept-defaults
     This function returns the definition of KEY in KEYMAP.  All the
     other functions described in this chapter that look up keys use
     `lookup-key'.  Here are examples:

          (lookup-key (current-global-map) "\C-x\C-f")
              => find-file
          (lookup-key (current-global-map) (kbd "C-x C-f"))
              => find-file
          (lookup-key (current-global-map) "\C-x\C-f12345")
              => 2

     If the string or vector KEY is not a valid key sequence according
     to the prefix keys specified in KEYMAP, it must be "too long" and
     have extra events at the end that do not fit into a single key
     sequence.  Then the value is a number, the number of events at the
     front of KEY that compose a complete key.

     If ACCEPT-DEFAULTS is non-`nil', then `lookup-key' considers
     default bindings as well as bindings for the specific events in
     KEY.  Otherwise, `lookup-key' reports only bindings for the
     specific sequence KEY, ignoring default bindings except when you
     explicitly ask about them.  (To do this, supply `t' as an element
     of KEY; see *note Format of Keymaps::.)

     If KEY contains a meta character (not a function key), that
     character is implicitly replaced by a two-character sequence: the
     value of `meta-prefix-char', followed by the corresponding non-meta
     character.  Thus, the first example below is handled by conversion
     into the second example.

          (lookup-key (current-global-map) "\M-f")
              => forward-word
          (lookup-key (current-global-map) "\ef")
              => forward-word

     Unlike `read-key-sequence', this function does not modify the
     specified events in ways that discard information (*note Key
     Sequence Input::).  In particular, it does not convert letters to
     lower case and it does not change drag events to clicks.

 -- Command: undefined
     Used in keymaps to undefine keys.  It calls `ding', but does not
     cause an error.

 -- Function: local-key-binding key &optional accept-defaults
     This function returns the binding for KEY in the current local
     keymap, or `nil' if it is undefined there.

     The argument ACCEPT-DEFAULTS controls checking for default
     bindings, as in `lookup-key' (above).

 -- Function: global-key-binding key &optional accept-defaults
     This function returns the binding for command KEY in the current
     global keymap, or `nil' if it is undefined there.

     The argument ACCEPT-DEFAULTS controls checking for default
     bindings, as in `lookup-key' (above).

 -- Function: minor-mode-key-binding key &optional accept-defaults
     This function returns a list of all the active minor mode bindings
     of KEY.  More precisely, it returns an alist of pairs `(MODENAME .
     BINDING)', where MODENAME is the variable that enables the minor
     mode, and BINDING is KEY's binding in that mode.  If KEY has no
     minor-mode bindings, the value is `nil'.

     If the first binding found is not a prefix definition (a keymap or
     a symbol defined as a keymap), all subsequent bindings from other
     minor modes are omitted, since they would be completely shadowed.
     Similarly, the list omits non-prefix bindings that follow prefix
     bindings.

     The argument ACCEPT-DEFAULTS controls checking for default
     bindings, as in `lookup-key' (above).

 -- User Option: meta-prefix-char
     This variable is the meta-prefix character code.  It is used for
     translating a meta character to a two-character sequence so it can
     be looked up in a keymap.  For useful results, the value should be
     a prefix event (*note Prefix Keys::).  The default value is 27,
     which is the ASCII code for <ESC>.

     As long as the value of `meta-prefix-char' remains 27, key lookup
     translates `M-b' into `<ESC> b', which is normally defined as the
     `backward-word' command.  However, if you were to set
     `meta-prefix-char' to 24, the code for `C-x', then Emacs will
     translate `M-b' into `C-x b', whose standard binding is the
     `switch-to-buffer' command.  (Don't actually do this!)  Here is an
     illustration of what would happen:

          meta-prefix-char                    ; The default value.
               => 27
          (key-binding "\M-b")
               => backward-word
          ?\C-x                               ; The print representation
               => 24                          ;   of a character.
          (setq meta-prefix-char 24)
               => 24
          (key-binding "\M-b")
               => switch-to-buffer            ; Now, typing `M-b' is
                                              ;   like typing `C-x b'.

          (setq meta-prefix-char 27)          ; Avoid confusion!
               => 27                          ; Restore the default value!

     This translation of one event into two happens only for
     characters, not for other kinds of input events.  Thus, `M-<F1>',
     a function key, is not converted into `<ESC> <F1>'.


File: elisp,  Node: Changing Key Bindings,  Next: Remapping Commands,  Prev: Functions for Key Lookup,  Up: Keymaps

22.12 Changing Key Bindings
===========================

The way to rebind a key is to change its entry in a keymap.  If you
change a binding in the global keymap, the change is effective in all
buffers (though it has no direct effect in buffers that shadow the
global binding with a local one).  If you change the current buffer's
local map, that usually affects all buffers using the same major mode.
The `global-set-key' and `local-set-key' functions are convenient
interfaces for these operations (*note Key Binding Commands::).  You
can also use `define-key', a more general function; then you must
explicitly specify the map to change.

   When choosing the key sequences for Lisp programs to rebind, please
follow the Emacs conventions for use of various keys (*note Key Binding
Conventions::).

   In writing the key sequence to rebind, it is good to use the special
escape sequences for control and meta characters (*note String Type::).
The syntax `\C-' means that the following character is a control
character and `\M-' means that the following character is a meta
character.  Thus, the string `"\M-x"' is read as containing a single
`M-x', `"\C-f"' is read as containing a single `C-f', and `"\M-\C-x"'
and `"\C-\M-x"' are both read as containing a single `C-M-x'.  You can
also use this escape syntax in vectors, as well as others that aren't
allowed in strings; one example is `[?\C-\H-x home]'.  *Note Character
Type::.

   The key definition and lookup functions accept an alternate syntax
for event types in a key sequence that is a vector: you can use a list
containing modifier names plus one base event (a character or function
key name).  For example, `(control ?a)' is equivalent to `?\C-a' and
`(hyper control left)' is equivalent to `C-H-left'.  One advantage of
such lists is that the precise numeric codes for the modifier bits
don't appear in compiled files.

   The functions below signal an error if KEYMAP is not a keymap, or if
KEY is not a string or vector representing a key sequence.  You can use
event types (symbols) as shorthand for events that are lists.  The
`kbd' macro (*note Key Sequences::) is a convenient way to specify the
key sequence.

 -- Function: define-key keymap key binding
     This function sets the binding for KEY in KEYMAP.  (If KEY is more
     than one event long, the change is actually made in another keymap
     reached from KEYMAP.)  The argument BINDING can be any Lisp
     object, but only certain types are meaningful.  (For a list of
     meaningful types, see *note Key Lookup::.)  The value returned by
     `define-key' is BINDING.

     If KEY is `[t]', this sets the default binding in KEYMAP.  When an
     event has no binding of its own, the Emacs command loop uses the
     keymap's default binding, if there is one.

     Every prefix of KEY must be a prefix key (i.e., bound to a keymap)
     or undefined; otherwise an error is signaled.  If some prefix of
     KEY is undefined, then `define-key' defines it as a prefix key so
     that the rest of KEY can be defined as specified.

     If there was previously no binding for KEY in KEYMAP, the new
     binding is added at the beginning of KEYMAP.  The order of
     bindings in a keymap makes no difference for keyboard input, but it
     does matter for menu keymaps (*note Menu Keymaps::).

   This example creates a sparse keymap and makes a number of bindings
in it:

     (setq map (make-sparse-keymap))
         => (keymap)
     (define-key map "\C-f" 'forward-char)
         => forward-char
     map
         => (keymap (6 . forward-char))

     ;; Build sparse submap for `C-x' and bind `f' in that.
     (define-key map (kbd "C-x f") 'forward-word)
         => forward-word
     map
     => (keymap
         (24 keymap                ; C-x
             (102 . forward-word)) ;      f
         (6 . forward-char))       ; C-f

     ;; Bind `C-p' to the `ctl-x-map'.
     (define-key map (kbd "C-p") ctl-x-map)
     ;; `ctl-x-map'
     => [nil ... find-file ... backward-kill-sentence]

     ;; Bind `C-f' to `foo' in the `ctl-x-map'.
     (define-key map (kbd "C-p C-f") 'foo)
     => 'foo
     map
     => (keymap     ; Note `foo' in `ctl-x-map'.
         (16 keymap [nil ... foo ... backward-kill-sentence])
         (24 keymap
             (102 . forward-word))
         (6 . forward-char))

Note that storing a new binding for `C-p C-f' actually works by
changing an entry in `ctl-x-map', and this has the effect of changing
the bindings of both `C-p C-f' and `C-x C-f' in the default global map.

   The function `substitute-key-definition' scans a keymap for keys
that have a certain binding and rebinds them with a different binding.
Another feature which is cleaner and can often produce the same results
to remap one command into another (*note Remapping Commands::).

 -- Function: substitute-key-definition olddef newdef keymap &optional
          oldmap
     This function replaces OLDDEF with NEWDEF for any keys in KEYMAP
     that were bound to OLDDEF.  In other words, OLDDEF is replaced
     with NEWDEF wherever it appears.  The function returns `nil'.

     For example, this redefines `C-x C-f', if you do it in an Emacs
     with standard bindings:

          (substitute-key-definition
           'find-file 'find-file-read-only (current-global-map))

     If OLDMAP is non-`nil', that changes the behavior of
     `substitute-key-definition': the bindings in OLDMAP determine
     which keys to rebind.  The rebindings still happen in KEYMAP, not
     in OLDMAP.  Thus, you can change one map under the control of the
     bindings in another.  For example,

          (substitute-key-definition
            'delete-backward-char 'my-funny-delete
            my-map global-map)

     puts the special deletion command in `my-map' for whichever keys
     are globally bound to the standard deletion command.

     Here is an example showing a keymap before and after substitution:

          (setq map '(keymap
                      (?1 . olddef-1)
                      (?2 . olddef-2)
                      (?3 . olddef-1)))
          => (keymap (49 . olddef-1) (50 . olddef-2) (51 . olddef-1))

          (substitute-key-definition 'olddef-1 'newdef map)
          => nil
          map
          => (keymap (49 . newdef) (50 . olddef-2) (51 . newdef))

 -- Function: suppress-keymap keymap &optional nodigits
     This function changes the contents of the full keymap KEYMAP by
     remapping `self-insert-command' to the command `undefined' (*note
     Remapping Commands::).  This has the effect of undefining all
     printing characters, thus making ordinary insertion of text
     impossible.  `suppress-keymap' returns `nil'.

     If NODIGITS is `nil', then `suppress-keymap' defines digits to run
     `digit-argument', and `-' to run `negative-argument'.  Otherwise
     it makes them undefined like the rest of the printing characters.

     The `suppress-keymap' function does not make it impossible to
     modify a buffer, as it does not suppress commands such as `yank'
     and `quoted-insert'.  To prevent any modification of a buffer, make
     it read-only (*note Read Only Buffers::).

     Since this function modifies KEYMAP, you would normally use it on
     a newly created keymap.  Operating on an existing keymap that is
     used for some other purpose is likely to cause trouble; for
     example, suppressing `global-map' would make it impossible to use
     most of Emacs.

     This function can be used to initialize the local keymap of a major
     mode for which insertion of text is not desirable.  But usually
     such a mode should be derived from `special-mode' (*note Basic
     Major Modes::); then its keymap will automatically inherit from
     `special-mode-map', which is already suppressed.  Here is how
     `special-mode-map' is defined:

          (defvar special-mode-map
            (let ((map (make-sparse-keymap)))
              (suppress-keymap map)
              (define-key map "q" 'quit-window)
              ...
              map))


File: elisp,  Node: Remapping Commands,  Next: Translation Keymaps,  Prev: Changing Key Bindings,  Up: Keymaps

22.13 Remapping Commands
========================

A special kind of key binding can be used to "remap" one command to
another, without having to refer to the key sequence(s) bound to the
original command.  To use this feature, make a key binding for a key
sequence that starts with the dummy event `remap', followed by the
command name you want to remap; for the binding, specify the new
definition (usually a command name, but possibly any other valid
definition for a key binding).

   For example, suppose My mode provides a special command
`my-kill-line', which should be invoked instead of `kill-line'.  To
establish this, its mode keymap should contain the following remapping:

     (define-key my-mode-map [remap kill-line] 'my-kill-line)

Then, whenever `my-mode-map' is active, if the user types `C-k' (the
default global key sequence for `kill-line') Emacs will instead run
`my-kill-line'.

   Note that remapping only takes place through active keymaps; for
example, putting a remapping in a prefix keymap like `ctl-x-map'
typically has no effect, as such keymaps are not themselves active.  In
addition, remapping only works through a single level; in the following
example,

     (define-key my-mode-map [remap kill-line] 'my-kill-line)
     (define-key my-mode-map [remap my-kill-line] 'my-other-kill-line)

`kill-line' is _not_ remapped to `my-other-kill-line'.  Instead, if an
ordinary key binding specifies `kill-line', it is remapped to
`my-kill-line'; if an ordinary binding specifies `my-kill-line', it is
remapped to `my-other-kill-line'.

   To undo the remapping of a command, remap it to `nil'; e.g.

     (define-key my-mode-map [remap kill-line] nil)

 -- Function: command-remapping command &optional position keymaps
     This function returns the remapping for COMMAND (a symbol), given
     the current active keymaps.  If COMMAND is not remapped (which is
     the usual situation), or not a symbol, the function returns `nil'.
     `position' can optionally specify a buffer position or an event
     position to determine the keymaps to use, as in `key-binding'.

     If the optional argument `keymaps' is non-`nil', it specifies a
     list of keymaps to search in.  This argument is ignored if
     `position' is non-`nil'.


File: elisp,  Node: Translation Keymaps,  Next: Key Binding Commands,  Prev: Remapping Commands,  Up: Keymaps

22.14 Keymaps for Translating Sequences of Events
=================================================

This section describes keymaps that are used during reading a key
sequence, to translate certain event sequences into others.
`read-key-sequence' checks every subsequence of the key sequence being
read, as it is read, against `input-decode-map', then
`local-function-key-map', and then against `key-translation-map'.

 -- Variable: input-decode-map
     This variable holds a keymap that describes the character
     sequences sent by function keys on an ordinary character terminal.
     This keymap has the same structure as other keymaps, but is used
     differently: it specifies translations to make while reading key
     sequences, rather than bindings for key sequences.

     If `input-decode-map' "binds" a key sequence K to a vector V, then
     when K appears as a subsequence _anywhere_ in a key sequence, it
     is replaced with the events in V.

     For example, VT100 terminals send `<ESC> O P' when the keypad
     <PF1> key is pressed.  Therefore, we want Emacs to translate that
     sequence of events into the single event `pf1'.  We accomplish
     this by "binding" `<ESC> O P' to `[pf1]' in `input-decode-map',
     when using a VT100.

     Thus, typing `C-c <PF1>' sends the character sequence `C-c <ESC> O
     P'; later the function `read-key-sequence' translates this back
     into `C-c <PF1>', which it returns as the vector `[?\C-c pf1]'.

     The value of `input-decode-map' is usually set up automatically
     according to the terminal's Terminfo or Termcap entry, but
     sometimes those need help from terminal-specific Lisp files.
     Emacs comes with terminal-specific files for many common
     terminals; their main purpose is to make entries in
     `input-decode-map' beyond those that can be deduced from Termcap
     and Terminfo.  *Note Terminal-Specific::.

 -- Variable: local-function-key-map
     This variable holds a keymap similar to `input-decode-map' except
     that it describes key sequences which should be translated to
     alternative interpretations that are usually preferred.  It applies
     after `input-decode-map' and before `key-translation-map'.

     Entries in `local-function-key-map' are ignored if they conflict
     with bindings made in the minor mode, local, or global keymaps.
     I.e.  the remapping only applies if the original key sequence would
     otherwise not have any binding.

     `local-function-key-map' inherits from `function-key-map', but the
     latter should not be used directly.

 -- Variable: key-translation-map
     This variable is another keymap used just like `input-decode-map'
     to translate input events into other events.  It differs from
     `input-decode-map' in that it goes to work after
     `local-function-key-map' is finished rather than before; it
     receives the results of translation by `local-function-key-map'.

     Just like `input-decode-map', but unlike `local-function-key-map',
     this keymap is applied regardless of whether the input
     key-sequence has a normal binding.  Note however that actual key
     bindings can have an effect on `key-translation-map', even though
     they are overridden by it.  Indeed, actual key bindings override
     `local-function-key-map' and thus may alter the key sequence that
     `key-translation-map' receives.  Clearly, it is better to avoid
     this type of situation.

     The intent of `key-translation-map' is for users to map one
     character set to another, including ordinary characters normally
     bound to `self-insert-command'.

   You can use `input-decode-map', `local-function-key-map', and
`key-translation-map' for more than simple aliases, by using a
function, instead of a key sequence, as the "translation" of a key.
Then this function is called to compute the translation of that key.

   The key translation function receives one argument, which is the
prompt that was specified in `read-key-sequence'--or `nil' if the key
sequence is being read by the editor command loop.  In most cases you
can ignore the prompt value.

   If the function reads input itself, it can have the effect of
altering the event that follows.  For example, here's how to define
`C-c h' to turn the character that follows into a Hyper character:

     (defun hyperify (prompt)
       (let ((e (read-event)))
         (vector (if (numberp e)
                     (logior (lsh 1 24) e)
                   (if (memq 'hyper (event-modifiers e))
                       e
                     (add-event-modifier "H-" e))))))

     (defun add-event-modifier (string e)
       (let ((symbol (if (symbolp e) e (car e))))
         (setq symbol (intern (concat string
                                      (symbol-name symbol))))
         (if (symbolp e)
             symbol
           (cons symbol (cdr e)))))

     (define-key local-function-key-map "\C-ch" 'hyperify)

   If you have enabled keyboard character set decoding using
`set-keyboard-coding-system', decoding is done after the translations
listed above.  *Note Terminal I/O Encoding::.  However, in future Emacs
versions, character set decoding may be done at an earlier stage.


File: elisp,  Node: Key Binding Commands,  Next: Scanning Keymaps,  Prev: Translation Keymaps,  Up: Keymaps

22.15 Commands for Binding Keys
===============================

This section describes some convenient interactive interfaces for
changing key bindings.  They work by calling `define-key'.

   People often use `global-set-key' in their init files (*note Init
File::) for simple customization.  For example,

     (global-set-key (kbd "C-x C-\\") 'next-line)

or

     (global-set-key [?\C-x ?\C-\\] 'next-line)

or

     (global-set-key [(control ?x) (control ?\\)] 'next-line)

redefines `C-x C-\' to move down a line.

     (global-set-key [M-mouse-1] 'mouse-set-point)

redefines the first (leftmost) mouse button, entered with the Meta key,
to set point where you click.

   Be careful when using non-ASCII text characters in Lisp
specifications of keys to bind.  If these are read as multibyte text, as
they usually will be in a Lisp file (*note Loading Non-ASCII::), you
must type the keys as multibyte too.  For instance, if you use this:

     (global-set-key "�" 'my-function) ; bind o-umlaut

or

     (global-set-key ?� 'my-function) ; bind o-umlaut

and your language environment is multibyte Latin-1, these commands
actually bind the multibyte character with code 246, not the byte code
246 (`M-v') sent by a Latin-1 terminal.  In order to use this binding,
you need to teach Emacs how to decode the keyboard by using an
appropriate input method (*note Input Methods: (emacs)Input Methods.).

 -- Command: global-set-key key binding
     This function sets the binding of KEY in the current global map to
     BINDING.

          (global-set-key KEY BINDING)
          ==
          (define-key (current-global-map) KEY BINDING)

 -- Command: global-unset-key key
     This function removes the binding of KEY from the current global
     map.

     One use of this function is in preparation for defining a longer
     key that uses KEY as a prefix--which would not be allowed if KEY
     has a non-prefix binding.  For example:

          (global-unset-key "\C-l")
              => nil
          (global-set-key "\C-l\C-l" 'redraw-display)
              => nil

     This function is implemented simply using `define-key':

          (global-unset-key KEY)
          ==
          (define-key (current-global-map) KEY nil)

 -- Command: local-set-key key binding
     This function sets the binding of KEY in the current local keymap
     to BINDING.

          (local-set-key KEY BINDING)
          ==
          (define-key (current-local-map) KEY BINDING)

 -- Command: local-unset-key key
     This function removes the binding of KEY from the current local
     map.

          (local-unset-key KEY)
          ==
          (define-key (current-local-map) KEY nil)


File: elisp,  Node: Scanning Keymaps,  Next: Menu Keymaps,  Prev: Key Binding Commands,  Up: Keymaps

22.16 Scanning Keymaps
======================

This section describes functions used to scan all the current keymaps
for the sake of printing help information.

 -- Function: accessible-keymaps keymap &optional prefix
     This function returns a list of all the keymaps that can be
     reached (via zero or more prefix keys) from KEYMAP.  The value is
     an association list with elements of the form `(KEY .  MAP)',
     where KEY is a prefix key whose definition in KEYMAP is MAP.

     The elements of the alist are ordered so that the KEY increases in
     length.  The first element is always `([] . KEYMAP)', because the
     specified keymap is accessible from itself with a prefix of no
     events.

     If PREFIX is given, it should be a prefix key sequence; then
     `accessible-keymaps' includes only the submaps whose prefixes start
     with PREFIX.  These elements look just as they do in the value of
     `(accessible-keymaps)'; the only difference is that some elements
     are omitted.

     In the example below, the returned alist indicates that the key
     <ESC>, which is displayed as `^[', is a prefix key whose
     definition is the sparse keymap `(keymap (83 . center-paragraph)
     (115 . foo))'.

          (accessible-keymaps (current-local-map))
          =>(([] keymap
                (27 keymap   ; Note this keymap for <ESC> is repeated below.
                    (83 . center-paragraph)
                    (115 . center-line))
                (9 . tab-to-tab-stop))

             ("^[" keymap
              (83 . center-paragraph)
              (115 . foo)))

     In the following example, `C-h' is a prefix key that uses a sparse
     keymap starting with `(keymap (118 . describe-variable)...)'.
     Another prefix, `C-x 4', uses a keymap which is also the value of
     the variable `ctl-x-4-map'.  The event `mode-line' is one of
     several dummy events used as prefixes for mouse actions in special
     parts of a window.

          (accessible-keymaps (current-global-map))
          => (([] keymap [set-mark-command beginning-of-line ...
                             delete-backward-char])
              ("^H" keymap (118 . describe-variable) ...
               (8 . help-for-help))
              ("^X" keymap [x-flush-mouse-queue ...
               backward-kill-sentence])
              ("^[" keymap [mark-sexp backward-sexp ...
               backward-kill-word])
              ("^X4" keymap (15 . display-buffer) ...)
              ([mode-line] keymap
               (S-mouse-2 . mouse-split-window-horizontally) ...))

     These are not all the keymaps you would see in actuality.

 -- Function: map-keymap function keymap
     The function `map-keymap' calls FUNCTION once for each binding in
     KEYMAP.  It passes two arguments, the event type and the value of
     the binding.  If KEYMAP has a parent, the parent's bindings are
     included as well.  This works recursively: if the parent has
     itself a parent, then the grandparent's bindings are also included
     and so on.

     This function is the cleanest way to examine all the bindings in a
     keymap.

 -- Function: where-is-internal command &optional keymap firstonly
          noindirect no-remap
     This function is a subroutine used by the `where-is' command
     (*note Help: (emacs)Help.).  It returns a list of all key
     sequences (of any length) that are bound to COMMAND in a set of
     keymaps.

     The argument COMMAND can be any object; it is compared with all
     keymap entries using `eq'.

     If KEYMAP is `nil', then the maps used are the current active
     keymaps, disregarding `overriding-local-map' (that is, pretending
     its value is `nil').  If KEYMAP is a keymap, then the maps
     searched are KEYMAP and the global keymap.  If KEYMAP is a list of
     keymaps, only those keymaps are searched.

     Usually it's best to use `overriding-local-map' as the expression
     for KEYMAP.  Then `where-is-internal' searches precisely the
     keymaps that are active.  To search only the global map, pass the
     value `(keymap)' (an empty keymap) as KEYMAP.

     If FIRSTONLY is `non-ascii', then the value is a single vector
     representing the first key sequence found, rather than a list of
     all possible key sequences.  If FIRSTONLY is `t', then the value
     is the first key sequence, except that key sequences consisting
     entirely of ASCII characters (or meta variants of ASCII
     characters) are preferred to all other key sequences and that the
     return value can never be a menu binding.

     If NOINDIRECT is non-`nil', `where-is-internal' doesn't follow
     indirect keymap bindings.  This makes it possible to search for an
     indirect definition itself.

     The fifth argument, NO-REMAP, determines how this function treats
     command remappings (*note Remapping Commands::).  There are two
     cases of interest:

    If a command OTHER-COMMAND is remapped to COMMAND:
          If NO-REMAP is `nil', find the bindings for OTHER-COMMAND and
          treat them as though they are also bindings for COMMAND.  If
          NO-REMAP is non-`nil', include the vector `[remap
          OTHER-COMMAND]' in the list of possible key sequences,
          instead of finding those bindings.

    If COMMAND is remapped to OTHER-COMMAND:
          If NO-REMAP is `nil', return the bindings for OTHER-COMMAND
          rather than COMMAND.  If NO-REMAP is non-`nil', return the
          bindings for COMMAND, ignoring the fact that it is remapped.

 -- Command: describe-bindings &optional prefix buffer-or-name
     This function creates a listing of all current key bindings, and
     displays it in a buffer named `*Help*'.  The text is grouped by
     modes--minor modes first, then the major mode, then global
     bindings.

     If PREFIX is non-`nil', it should be a prefix key; then the
     listing includes only keys that start with PREFIX.

     The listing describes meta characters as <ESC> followed by the
     corresponding non-meta character.

     When several characters with consecutive ASCII codes have the same
     definition, they are shown together, as `FIRSTCHAR..LASTCHAR'.  In
     this instance, you need to know the ASCII codes to understand
     which characters this means.  For example, in the default global
     map, the characters `<SPC> .. ~' are described by a single line.
     <SPC> is ASCII 32, `~' is ASCII 126, and the characters between
     them include all the normal printing characters, (e.g., letters,
     digits, punctuation, etc.); all these characters are bound to
     `self-insert-command'.

     If BUFFER-OR-NAME is non-`nil', it should be a buffer or a buffer
     name.  Then `describe-bindings' lists that buffer's bindings,
     instead of the current buffer's.


File: elisp,  Node: Menu Keymaps,  Prev: Scanning Keymaps,  Up: Keymaps

22.17 Menu Keymaps
==================

A keymap can operate as a menu as well as defining bindings for
keyboard keys and mouse buttons.  Menus are usually actuated with the
mouse, but they can function with the keyboard also.  If a menu keymap
is active for the next input event, that activates the keyboard menu
feature.

* Menu:

* Defining Menus::              How to make a keymap that defines a menu.
* Mouse Menus::                 How users actuate the menu with the mouse.
* Keyboard Menus::              How users actuate the menu with the keyboard.
* Menu Example::                Making a simple menu.
* Menu Bar::                    How to customize the menu bar.
* Tool Bar::                    A tool bar is a row of images.
* Modifying Menus::             How to add new items to a menu.


File: elisp,  Node: Defining Menus,  Next: Mouse Menus,  Up: Menu Keymaps

22.17.1 Defining Menus
----------------------

A keymap acts as a menu if it has an "overall prompt string", which is
a string that appears as an element of the keymap.  (*Note Format of
Keymaps::.)  The string should describe the purpose of the menu's
commands.  Emacs displays the overall prompt string as the menu title
in some cases, depending on the toolkit (if any) used for displaying
menus.(1)  Keyboard menus also display the overall prompt string.

   The easiest way to construct a keymap with a prompt string is to
specify the string as an argument when you call `make-keymap',
`make-sparse-keymap' (*note Creating Keymaps::), or
`define-prefix-command' (*note Definition of define-prefix-command::).
If you do not want the keymap to operate as a menu, don't specify a
prompt string for it.

 -- Function: keymap-prompt keymap
     This function returns the overall prompt string of KEYMAP, or
     `nil' if it has none.

   The menu's items are the bindings in the keymap.  Each binding
associates an event type to a definition, but the event types have no
significance for the menu appearance.  (Usually we use pseudo-events,
symbols that the keyboard cannot generate, as the event types for menu
item bindings.)  The menu is generated entirely from the bindings that
correspond in the keymap to these events.

   The order of items in the menu is the same as the order of bindings
in the keymap.  Since `define-key' puts new bindings at the front, you
should define the menu items starting at the bottom of the menu and
moving to the top, if you care about the order.  When you add an item to
an existing menu, you can specify its position in the menu using
`define-key-after' (*note Modifying Menus::).

* Menu:

* Simple Menu Items::       A simple kind of menu key binding,
                              limited in capabilities.
* Extended Menu Items::     More powerful menu item definitions
                              let you specify keywords to enable
                              various features.
* Menu Separators::         Drawing a horizontal line through a menu.
* Alias Menu Items::        Using command aliases in menu items.
* Toolkit Differences::     Not all toolkits provide the same features.

   ---------- Footnotes ----------

   (1) It is required for menus which do not use a toolkit, e.g. under
MS-DOS.


File: elisp,  Node: Simple Menu Items,  Next: Extended Menu Items,  Up: Defining Menus

22.17.1.1 Simple Menu Items
...........................

The simpler (and original) way to define a menu item is to bind some
event type (it doesn't matter what event type) to a binding like this:

     (ITEM-STRING . REAL-BINDING)

The CAR, ITEM-STRING, is the string to be displayed in the menu.  It
should be short--preferably one to three words.  It should describe the
action of the command it corresponds to.  Note that not all graphical
toolkits can display non-ASCII text in menus (it will work for keyboard
menus and will work to a large extent with the GTK+ toolkit).

   You can also supply a second string, called the help string, as
follows:

     (ITEM-STRING HELP . REAL-BINDING)

HELP specifies a "help-echo" string to display while the mouse is on
that item in the same way as `help-echo' text properties (*note Help
display::).

   As far as `define-key' is concerned, ITEM-STRING and HELP-STRING are
part of the event's binding.  However, `lookup-key' returns just
REAL-BINDING, and only REAL-BINDING is used for executing the key.

   If REAL-BINDING is `nil', then ITEM-STRING appears in the menu but
cannot be selected.

   If REAL-BINDING is a symbol and has a non-`nil' `menu-enable'
property, that property is an expression that controls whether the menu
item is enabled.  Every time the keymap is used to display a menu,
Emacs evaluates the expression, and it enables the menu item only if
the expression's value is non-`nil'.  When a menu item is disabled, it
is displayed in a "fuzzy" fashion, and cannot be selected.

   The menu bar does not recalculate which items are enabled every time
you look at a menu.  This is because the X toolkit requires the whole
tree of menus in advance.  To force recalculation of the menu bar, call
`force-mode-line-update' (*note Mode Line Format::).


File: elisp,  Node: Extended Menu Items,  Next: Menu Separators,  Prev: Simple Menu Items,  Up: Defining Menus

22.17.1.2 Extended Menu Items
.............................

An extended-format menu item is a more flexible and also cleaner
alternative to the simple format.  You define an event type with a
binding that's a list starting with the symbol `menu-item'.  For a
non-selectable string, the binding looks like this:

     (menu-item ITEM-NAME)

A string starting with two or more dashes specifies a separator line;
see *note Menu Separators::.

   To define a real menu item which can be selected, the extended format
binding looks like this:

     (menu-item ITEM-NAME REAL-BINDING
         . ITEM-PROPERTY-LIST)

Here, ITEM-NAME is an expression which evaluates to the menu item
string.  Thus, the string need not be a constant.  The third element,
REAL-BINDING, is the command to execute.  The tail of the list,
ITEM-PROPERTY-LIST, has the form of a property list which contains
other information.

   Here is a table of the properties that are supported:

`:enable FORM'
     The result of evaluating FORM determines whether the item is
     enabled (non-`nil' means yes).  If the item is not enabled, you
     can't really click on it.

`:visible FORM'
     The result of evaluating FORM determines whether the item should
     actually appear in the menu (non-`nil' means yes).  If the item
     does not appear, then the menu is displayed as if this item were
     not defined at all.

`:help HELP'
     The value of this property, HELP, specifies a "help-echo" string
     to display while the mouse is on that item.  This is displayed in
     the same way as `help-echo' text properties (*note Help display::).
     Note that this must be a constant string, unlike the `help-echo'
     property for text and overlays.

`:button (TYPE . SELECTED)'
     This property provides a way to define radio buttons and toggle
     buttons.  The CAR, TYPE, says which: it should be `:toggle' or
     `:radio'.  The CDR, SELECTED, should be a form; the result of
     evaluating it says whether this button is currently selected.

     A "toggle" is a menu item which is labeled as either "on" or "off"
     according to the value of SELECTED.  The command itself should
     toggle SELECTED, setting it to `t' if it is `nil', and to `nil' if
     it is `t'.  Here is how the menu item to toggle the
     `debug-on-error' flag is defined:

          (menu-item "Debug on Error" toggle-debug-on-error
                     :button (:toggle
                              . (and (boundp 'debug-on-error)
                                     debug-on-error)))

     This works because `toggle-debug-on-error' is defined as a command
     which toggles the variable `debug-on-error'.

     "Radio buttons" are a group of menu items, in which at any time one
     and only one is "selected".  There should be a variable whose value
     says which one is selected at any time.  The SELECTED form for
     each radio button in the group should check whether the variable
     has the right value for selecting that button.  Clicking on the
     button should set the variable so that the button you clicked on
     becomes selected.

`:key-sequence KEY-SEQUENCE'
     This property specifies which key sequence is likely to be bound
     to the same command invoked by this menu item.  If you specify the
     right key sequence, that makes preparing the menu for display run
     much faster.

     If you specify the wrong key sequence, it has no effect; before
     Emacs displays KEY-SEQUENCE in the menu, it verifies that
     KEY-SEQUENCE is really equivalent to this menu item.

`:key-sequence nil'
     This property indicates that there is normally no key binding
     which is equivalent to this menu item.  Using this property saves
     time in preparing the menu for display, because Emacs does not
     need to search the keymaps for a keyboard equivalent for this menu
     item.

     However, if the user has rebound this item's definition to a key
     sequence, Emacs ignores the `:keys' property and finds the keyboard
     equivalent anyway.

`:keys STRING'
     This property specifies that STRING is the string to display as
     the keyboard equivalent for this menu item.  You can use the
     `\\[...]' documentation construct in STRING.

`:filter FILTER-FN'
     This property provides a way to compute the menu item dynamically.
     The property value FILTER-FN should be a function of one argument;
     when it is called, its argument will be REAL-BINDING.  The
     function should return the binding to use instead.

     Emacs can call this function at any time that it does redisplay or
     operates on menu data structures, so you should write it so it can
     safely be called at any time.


File: elisp,  Node: Menu Separators,  Next: Alias Menu Items,  Prev: Extended Menu Items,  Up: Defining Menus

22.17.1.3 Menu Separators
.........................

A menu separator is a kind of menu item that doesn't display any
text--instead, it divides the menu into subparts with a horizontal line.
A separator looks like this in the menu keymap:

     (menu-item SEPARATOR-TYPE)

where SEPARATOR-TYPE is a string starting with two or more dashes.

   In the simplest case, SEPARATOR-TYPE consists of only dashes.  That
specifies the default kind of separator.  (For compatibility, `""' and
`-' also count as separators.)

   Certain other values of SEPARATOR-TYPE specify a different style of
separator.  Here is a table of them:

`"--no-line"'
`"--space"'
     An extra vertical space, with no actual line.

`"--single-line"'
     A single line in the menu's foreground color.

`"--double-line"'
     A double line in the menu's foreground color.

`"--single-dashed-line"'
     A single dashed line in the menu's foreground color.

`"--double-dashed-line"'
     A double dashed line in the menu's foreground color.

`"--shadow-etched-in"'
     A single line with a 3D sunken appearance.  This is the default,
     used separators consisting of dashes only.

`"--shadow-etched-out"'
     A single line with a 3D raised appearance.

`"--shadow-etched-in-dash"'
     A single dashed line with a 3D sunken appearance.

`"--shadow-etched-out-dash"'
     A single dashed line with a 3D raised appearance.

`"--shadow-double-etched-in"'
     Two lines with a 3D sunken appearance.

`"--shadow-double-etched-out"'
     Two lines with a 3D raised appearance.

`"--shadow-double-etched-in-dash"'
     Two dashed lines with a 3D sunken appearance.

`"--shadow-double-etched-out-dash"'
     Two dashed lines with a 3D raised appearance.

   You can also give these names in another style, adding a colon after
the double-dash and replacing each single dash with capitalization of
the following word.  Thus, `"--:singleLine"', is equivalent to
`"--single-line"'.

   You can use a longer form to specify keywords such as `:enable' and
`:visible' for a menu separator:

   `(menu-item SEPARATOR-TYPE nil . ITEM-PROPERTY-LIST)'

   For example:

     (menu-item "--" nil :visible (boundp 'foo))

   Some systems and display toolkits don't really handle all of these
separator types.  If you use a type that isn't supported, the menu
displays a similar kind of separator that is supported.


File: elisp,  Node: Alias Menu Items,  Next: Toolkit Differences,  Prev: Menu Separators,  Up: Defining Menus

22.17.1.4 Alias Menu Items
..........................

Sometimes it is useful to make menu items that use the "same" command
but with different enable conditions.  The best way to do this in Emacs
now is with extended menu items; before that feature existed, it could
be done by defining alias commands and using them in menu items.
Here's an example that makes two aliases for `toggle-read-only' and
gives them different enable conditions:

     (defalias 'make-read-only 'toggle-read-only)
     (put 'make-read-only 'menu-enable '(not buffer-read-only))
     (defalias 'make-writable 'toggle-read-only)
     (put 'make-writable 'menu-enable 'buffer-read-only)

   When using aliases in menus, often it is useful to display the
equivalent key bindings for the "real" command name, not the aliases
(which typically don't have any key bindings except for the menu
itself).  To request this, give the alias symbol a non-`nil'
`menu-alias' property.  Thus,

     (put 'make-read-only 'menu-alias t)
     (put 'make-writable 'menu-alias t)

causes menu items for `make-read-only' and `make-writable' to show the
keyboard bindings for `toggle-read-only'.


File: elisp,  Node: Toolkit Differences,  Prev: Alias Menu Items,  Up: Defining Menus

22.17.1.5 Toolkit Differences
.............................

The various toolkits with which you can build Emacs do not all support
the same set of features for menus.  Some code works as expected with
one toolkit, but not under another.

   One example is menu actions or buttons in a top-level menu bar.  The
following works with the Lucid toolkit or on MS Windows, but not with
GTK or Nextstep, where clicking on the item has no effect.

     (defun menu-action-greet ()
        (interactive)
        (message "Hello Emacs User!"))

     (defun top-level-menu ()
       (interactive)
       (define-key lisp-interaction-mode-map [menu-bar m]
          '(menu-item "Action Button" menu-action-greet)))


File: elisp,  Node: Mouse Menus,  Next: Keyboard Menus,  Prev: Defining Menus,  Up: Menu Keymaps

22.17.2 Menus and the Mouse
---------------------------

The usual way to make a menu keymap produce a menu is to make it the
definition of a prefix key.  (A Lisp program can explicitly pop up a
menu and receive the user's choice--see *note Pop-Up Menus::.)

   If the prefix key ends with a mouse event, Emacs handles the menu
keymap by popping up a visible menu, so that the user can select a
choice with the mouse.  When the user clicks on a menu item, the event
generated is whatever character or symbol has the binding that brought
about that menu item.  (A menu item may generate a series of events if
the menu has multiple levels or comes from the menu bar.)

   It's often best to use a button-down event to trigger the menu.  Then
the user can select a menu item by releasing the button.

   If the menu keymap contains a binding to a nested keymap, the nested
keymap specifies a "submenu".  There will be a menu item, labeled by
the nested keymap's item string, and clicking on this item
automatically pops up the specified submenu.  As a special exception,
if the menu keymap contains a single nested keymap and no other menu
items, the menu shows the contents of the nested keymap directly, not
as a submenu.

   However, if Emacs is compiled without X toolkit support, submenus
are not supported.  Each nested keymap is shown as a menu item, but
clicking on it does not automatically pop up the submenu.  If you wish
to imitate the effect of submenus, you can do that by giving a nested
keymap an item string which starts with `@'.  This causes Emacs to
display the nested keymap using a separate "menu pane"; the rest of the
item string after the `@' is the pane label.  If Emacs is compiled
without X toolkit support, menu panes are not used; in that case, a `@'
at the beginning of an item string is omitted when the menu label is
displayed, and has no other effect.


File: elisp,  Node: Keyboard Menus,  Next: Menu Example,  Prev: Mouse Menus,  Up: Menu Keymaps

22.17.3 Menus and the Keyboard
------------------------------

When a prefix key ending with a keyboard event (a character or function
key) has a definition that is a menu keymap, the keymap operates as a
keyboard menu; the user specifies the next event by choosing a menu
item with the keyboard.

   Emacs displays the keyboard menu with the map's overall prompt
string, followed by the alternatives (the item strings of the map's
bindings), in the echo area.  If the bindings don't all fit at once,
the user can type <SPC> to see the next line of alternatives.
Successive uses of <SPC> eventually get to the end of the menu and then
cycle around to the beginning.  (The variable `menu-prompt-more-char'
specifies which character is used for this; <SPC> is the default.)

   When the user has found the desired alternative from the menu, he or
she should type the corresponding character--the one whose binding is
that alternative.

 -- Variable: menu-prompt-more-char
     This variable specifies the character to use to ask to see the
     next line of a menu.  Its initial value is 32, the code for <SPC>.


File: elisp,  Node: Menu Example,  Next: Menu Bar,  Prev: Keyboard Menus,  Up: Menu Keymaps

22.17.4 Menu Example
--------------------

Here is a complete example of defining a menu keymap.  It is the
definition of the `Replace' submenu in the `Edit' menu in the menu bar,
and it uses the extended menu item format (*note Extended Menu
Items::).  First we create the keymap, and give it a name:

     (defvar menu-bar-replace-menu (make-sparse-keymap "Replace"))

Next we define the menu items:

     (define-key menu-bar-replace-menu [tags-repl-continue]
       '(menu-item "Continue Replace" tags-loop-continue
                   :help "Continue last tags replace operation"))
     (define-key menu-bar-replace-menu [tags-repl]
       '(menu-item "Replace in tagged files" tags-query-replace
                   :help "Interactively replace a regexp in all tagged files"))
     (define-key menu-bar-replace-menu [separator-replace-tags]
       '(menu-item "--"))
     ;; ...

Note the symbols which the bindings are "made for"; these appear inside
square brackets, in the key sequence being defined.  In some cases,
this symbol is the same as the command name; sometimes it is different.
These symbols are treated as "function keys", but they are not real
function keys on the keyboard.  They do not affect the functioning of
the menu itself, but they are "echoed" in the echo area when the user
selects from the menu, and they appear in the output of `where-is' and
`apropos'.

   The menu in this example is intended for use with the mouse.  If a
menu is intended for use with the keyboard, that is, if it is bound to
a key sequence ending with a keyboard event, then the menu items should
be bound to characters or "real" function keys, that can be typed with
the keyboard.

   The binding whose definition is `("--")' is a separator line.  Like
a real menu item, the separator has a key symbol, in this case
`separator-replace-tags'.  If one menu has two separators, they must
have two different key symbols.

   Here is how we make this menu appear as an item in the parent menu:

     (define-key menu-bar-edit-menu [replace]
       (list 'menu-item "Replace" menu-bar-replace-menu))

Note that this incorporates the submenu keymap, which is the value of
the variable `menu-bar-replace-menu', rather than the symbol
`menu-bar-replace-menu' itself.  Using that symbol in the parent menu
item would be meaningless because `menu-bar-replace-menu' is not a
command.

   If you wanted to attach the same replace menu to a mouse click, you
can do it this way:

     (define-key global-map [C-S-down-mouse-1]
        menu-bar-replace-menu)


File: elisp,  Node: Menu Bar,  Next: Tool Bar,  Prev: Menu Example,  Up: Menu Keymaps

22.17.5 The Menu Bar
--------------------

On graphical displays, there is usually a "menu bar" at the top of each
frame.  *Note Menu Bars: (emacs)Menu Bars.  Menu bar items are
subcommands of the fake "function key" `menu-bar', as defined in the
active keymaps.

   To add an item to the menu bar, invent a fake "function key" of your
own (let's call it KEY), and make a binding for the key sequence
`[menu-bar KEY]'.  Most often, the binding is a menu keymap, so that
pressing a button on the menu bar item leads to another menu.

   When more than one active keymap defines the same "function key" for
the menu bar, the item appears just once.  If the user clicks on that
menu bar item, it brings up a single, combined menu containing all the
subcommands of that item--the global subcommands, the local
subcommands, and the minor mode subcommands.

   The variable `overriding-local-map' is normally ignored when
determining the menu bar contents.  That is, the menu bar is computed
from the keymaps that would be active if `overriding-local-map' were
`nil'.  *Note Active Keymaps::.

   Here's an example of setting up a menu bar item:

     ;; Make a menu keymap (with a prompt string)
     ;; and make it the menu bar item's definition.
     (define-key global-map [menu-bar words]
       (cons "Words" (make-sparse-keymap "Words")))

     ;; Define specific subcommands in this menu.
     (define-key global-map
       [menu-bar words forward]
       '("Forward word" . forward-word))
     (define-key global-map
       [menu-bar words backward]
       '("Backward word" . backward-word))

   A local keymap can cancel a menu bar item made by the global keymap
by rebinding the same fake function key with `undefined' as the
binding.  For example, this is how Dired suppresses the `Edit' menu bar
item:

     (define-key dired-mode-map [menu-bar edit] 'undefined)

Here, `edit' is the fake function key used by the global map for the
`Edit' menu bar item.  The main reason to suppress a global menu bar
item is to regain space for mode-specific items.

 -- Variable: menu-bar-final-items
     Normally the menu bar shows global items followed by items defined
     by the local maps.

     This variable holds a list of fake function keys for items to
     display at the end of the menu bar rather than in normal sequence.
     The default value is `(help-menu)'; thus, the `Help' menu item
     normally appears at the end of the menu bar, following local menu
     items.

 -- Variable: menu-bar-update-hook
     This normal hook is run by redisplay to update the menu bar
     contents, before redisplaying the menu bar.  You can use it to
     update submenus whose contents should vary.  Since this hook is
     run frequently, we advise you to ensure that the functions it
     calls do not take much time in the usual case.

   Next to every menu bar item, Emacs displays a key binding that runs
the same command (if such a key binding exists).  This serves as a
convenient hint for users who do not know the key binding.  If a
command has multiple bindings, Emacs normally displays the first one it
finds.  You can specify one particular key binding by assigning an
`:advertised-binding' symbol property to the command.  *Note Keys in
Documentation::.


File: elisp,  Node: Tool Bar,  Next: Modifying Menus,  Prev: Menu Bar,  Up: Menu Keymaps

22.17.6 Tool bars
-----------------

A "tool bar" is a row of clickable icons at the top of a frame, just
below the menu bar.  *Note Tool Bars: (emacs)Tool Bars.

   On each frame, the frame parameter `tool-bar-lines' controls how
many lines' worth of height to reserve for the tool bar.  A zero value
suppresses the tool bar.  If the value is nonzero, and
`auto-resize-tool-bars' is non-`nil', the tool bar expands and
contracts automatically as needed to hold the specified contents.  If
the value is `grow-only', the tool bar expands automatically, but does
not contract automatically.

   The tool bar contents are controlled by a menu keymap attached to a
fake "function key" called `tool-bar' (much like the way the menu bar
is controlled).  So you define a tool bar item using `define-key', like
this:

     (define-key global-map [tool-bar KEY] ITEM)

where KEY is a fake "function key" to distinguish this item from other
items, and ITEM is a menu item key binding (*note Extended Menu
Items::), which says how to display this item and how it behaves.

   The usual menu keymap item properties, `:visible', `:enable',
`:button', and `:filter', are useful in tool bar bindings and have
their normal meanings.  The REAL-BINDING in the item must be a command,
not a keymap; in other words, it does not work to define a tool bar
icon as a prefix key.

   The `:help' property specifies a "help-echo" string to display while
the mouse is on that item.  This is displayed in the same way as
`help-echo' text properties (*note Help display::).

   In addition, you should use the `:image' property; this is how you
specify the image to display in the tool bar:

`:image IMAGE'
     IMAGES is either a single image specification or a vector of four
     image specifications.  If you use a vector of four, one of them is
     used, depending on circumstances:

    item 0
          Used when the item is enabled and selected.

    item 1
          Used when the item is enabled and deselected.

    item 2
          Used when the item is disabled and selected.

    item 3
          Used when the item is disabled and deselected.

   If IMAGE is a single image specification, Emacs draws the tool bar
button in disabled state by applying an edge-detection algorithm to the
image.

   The `:rtl' property specifies an alternative image to use for
right-to-left languages.  Only the GTK+ version of Emacs supports this
at present.

   Like the menu bar, the tool bar can display separators (*note Menu
Separators::).  Tool bar separators are vertical rather than
horizontal, though, and only a single style is supported.  They are
represented in the tool bar keymap by `(menu-item "--")' entries;
properties like `:visible' are not supported for tool bar separators.
Separators are rendered natively in GTK+ and Nextstep tool bars; in the
other cases, they are rendered using an image of a vertical line.

   The default tool bar is defined so that items specific to editing do
not appear for major modes whose command symbol has a `mode-class'
property of `special' (*note Major Mode Conventions::).  Major modes
may add items to the global bar by binding `[tool-bar FOO]' in their
local map.  It makes sense for some major modes to replace the default
tool bar items completely, since not many can be accommodated
conveniently, and the default bindings make this easy by using an
indirection through `tool-bar-map'.

 -- Variable: tool-bar-map
     By default, the global map binds `[tool-bar]' as follows:

          (global-set-key [tool-bar]
          		`(menu-item ,(purecopy "tool bar") ignore
          			    :filter tool-bar-make-keymap))

     The function `tool-bar-make-keymap', in turn, derives the actual
     tool bar map dynamically from the value of the variable
     `tool-bar-map'.  Hence, you should normally adjust the default
     (global) tool bar by changing that map.  Some major modes, such as
     Info mode, completely replace the global tool bar by making
     `tool-bar-map' buffer-local and setting it to a different keymap.

   There are two convenience functions for defining tool bar items, as
follows.

 -- Function: tool-bar-add-item icon def key &rest props
     This function adds an item to the tool bar by modifying
     `tool-bar-map'.  The image to use is defined by ICON, which is the
     base name of an XPM, XBM or PBM image file to be located by
     `find-image'.  Given a value `"exit"', say, `exit.xpm', `exit.pbm'
     and `exit.xbm' would be searched for in that order on a color
     display.  On a monochrome display, the search order is `.pbm',
     `.xbm' and `.xpm'.  The binding to use is the command DEF, and KEY
     is the fake function key symbol in the prefix keymap.  The
     remaining arguments PROPS are additional property list elements to
     add to the menu item specification.

     To define items in some local map, bind `tool-bar-map' with `let'
     around calls of this function:
          (defvar foo-tool-bar-map
            (let ((tool-bar-map (make-sparse-keymap)))
              (tool-bar-add-item ...)
              ...
              tool-bar-map))

 -- Function: tool-bar-add-item-from-menu command icon &optional map
          &rest props
     This function is a convenience for defining tool bar items which
     are consistent with existing menu bar bindings.  The binding of
     COMMAND is looked up in the menu bar in MAP (default `global-map')
     and modified to add an image specification for ICON, which is
     found in the same way as by `tool-bar-add-item'.  The resulting
     binding is then placed in `tool-bar-map', so use this function
     only for global tool bar items.

     MAP must contain an appropriate keymap bound to `[menu-bar]'.  The
     remaining arguments PROPS are additional property list elements to
     add to the menu item specification.

 -- Function: tool-bar-local-item-from-menu command icon in-map
          &optional from-map &rest props
     This function is used for making non-global tool bar items.  Use it
     like `tool-bar-add-item-from-menu' except that IN-MAP specifies
     the local map to make the definition in.  The argument FROM-MAP is
     like the MAP argument of `tool-bar-add-item-from-menu'.

 -- Variable: auto-resize-tool-bars
     If this variable is non-`nil', the tool bar automatically resizes
     to show all defined tool bar items--but not larger than a quarter
     of the frame's height.

     If the value is `grow-only', the tool bar expands automatically,
     but does not contract automatically.  To contract the tool bar, the
     user has to redraw the frame by entering `C-l'.

     If Emacs is built with GTK or Nextstep, the tool bar can only show
     one line, so this variable has no effect.

 -- Variable: auto-raise-tool-bar-buttons
     If this variable is non-`nil', tool bar items display in raised
     form when the mouse moves over them.

 -- Variable: tool-bar-button-margin
     This variable specifies an extra margin to add around tool bar
     items.  The value is an integer, a number of pixels.  The default
     is 4.

 -- Variable: tool-bar-button-relief
     This variable specifies the shadow width for tool bar items.  The
     value is an integer, a number of pixels.  The default is 1.

 -- Variable: tool-bar-border
     This variable specifies the height of the border drawn below the
     tool bar area.  An integer value specifies height as a number of
     pixels.  If the value is one of `internal-border-width' (the
     default) or `border-width', the tool bar border height corresponds
     to the corresponding frame parameter.

   You can define a special meaning for clicking on a tool bar item with
the shift, control, meta, etc., modifiers.  You do this by setting up
additional items that relate to the original item through the fake
function keys.  Specifically, the additional items should use the
modified versions of the same fake function key used to name the
original item.

   Thus, if the original item was defined this way,

     (define-key global-map [tool-bar shell]
       '(menu-item "Shell" shell
                   :image (image :type xpm :file "shell.xpm")))

then here is how you can define clicking on the same tool bar image with
the shift modifier:

     (define-key global-map [tool-bar S-shell] 'some-command)

   *Note Function Keys::, for more information about how to add
modifiers to function keys.


File: elisp,  Node: Modifying Menus,  Prev: Tool Bar,  Up: Menu Keymaps

22.17.7 Modifying Menus
-----------------------

When you insert a new item in an existing menu, you probably want to
put it in a particular place among the menu's existing items.  If you
use `define-key' to add the item, it normally goes at the front of the
menu.  To put it elsewhere in the menu, use `define-key-after':

 -- Function: define-key-after map key binding &optional after
     Define a binding in MAP for KEY, with value BINDING, just like
     `define-key', but position the binding in MAP after the binding
     for the event AFTER.  The argument KEY should be of length one--a
     vector or string with just one element.  But AFTER should be a
     single event type--a symbol or a character, not a sequence.  The
     new binding goes after the binding for AFTER.  If AFTER is `t' or
     is omitted, then the new binding goes last, at the end of the
     keymap.  However, new bindings are added before any inherited
     keymap.

     Here is an example:

          (define-key-after my-menu [drink]
            '("Drink" . drink-command) 'eat)

     makes a binding for the fake function key <DRINK> and puts it
     right after the binding for <EAT>.

     Here is how to insert an item called `Work' in the `Signals' menu
     of Shell mode, after the item `break':

          (define-key-after
            (lookup-key shell-mode-map [menu-bar signals])
            [work] '("Work" . work-command) 'break)


File: elisp,  Node: Modes,  Next: Documentation,  Prev: Keymaps,  Up: Top

23 Major and Minor Modes
************************

A "mode" is a set of definitions that customize Emacs and can be turned
on and off while you edit.  There are two varieties of modes: "major
modes", which are mutually exclusive and used for editing particular
kinds of text, and "minor modes", which provide features that users can
enable individually.

   This chapter describes how to write both major and minor modes, how
to indicate them in the mode line, and how they run hooks supplied by
the user.  For related topics such as keymaps and syntax tables, see
*note Keymaps::, and *note Syntax Tables::.

* Menu:

* Hooks::             How to use hooks; how to write code that provides hooks.
* Major Modes::       Defining major modes.
* Minor Modes::       Defining minor modes.
* Mode Line Format::  Customizing the text that appears in the mode line.
* Imenu::             Providing a menu of definitions made in a buffer.
* Font Lock Mode::    How modes can highlight text according to syntax.
* Auto-Indentation::  How to teach Emacs to indent for a major mode.
* Desktop Save Mode:: How modes can have buffer state saved between
                        Emacs sessions.


File: elisp,  Node: Hooks,  Next: Major Modes,  Up: Modes

23.1 Hooks
==========

A "hook" is a variable where you can store a function or functions to
be called on a particular occasion by an existing program.  Emacs
provides hooks for the sake of customization.  Most often, hooks are set
up in the init file (*note Init File::), but Lisp programs can set them
also.  *Note Standard Hooks::, for a list of some standard hook
variables.

   Most of the hooks in Emacs are "normal hooks".  These variables
contain lists of functions to be called with no arguments.  By
convention, whenever the hook name ends in `-hook', that tells you it
is normal.  We try to make all hooks normal, as much as possible, so
that you can use them in a uniform way.

   Every major mode command is supposed to run a normal hook called the
"mode hook" as one of the last steps of initialization.  This makes it
easy for a user to customize the behavior of the mode, by overriding
the buffer-local variable assignments already made by the mode.  Most
minor mode functions also run a mode hook at the end.  But hooks are
used in other contexts too.  For example, the hook `suspend-hook' runs
just before Emacs suspends itself (*note Suspending Emacs::).

   The recommended way to add a hook function to a hook is by calling
`add-hook' (*note Setting Hooks::).  The hook functions may be any of
the valid kinds of functions that `funcall' accepts (*note What Is a
Function::).  Most normal hook variables are initially void; `add-hook'
knows how to deal with this.  You can add hooks either globally or
buffer-locally with `add-hook'.

   If the hook variable's name does not end with `-hook', that
indicates it is probably an "abnormal hook".  That means the hook
functions are called with arguments, or their return values are used in
some way.  The hook's documentation says how the functions are called.
You can use `add-hook' to add a function to an abnormal hook, but you
must write the function to follow the hook's calling convention.

   By convention, abnormal hook names end in `-functions' or `-hooks'.
If the variable's name ends in `-function', then its value is just a
single function, not a list of functions.

* Menu:

* Running Hooks::    How to run a hook.
* Setting Hooks::    How to put functions on a hook, or remove them.


File: elisp,  Node: Running Hooks,  Next: Setting Hooks,  Up: Hooks

23.1.1 Running Hooks
--------------------

In this section, we document the `run-hooks' function, which is used to
run a normal hook.  We also document the functions for running various
kinds of abnormal hooks.

 -- Function: run-hooks &rest hookvars
     This function takes one or more normal hook variable names as
     arguments, and runs each hook in turn.  Each argument should be a
     symbol that is a normal hook variable.  These arguments are
     processed in the order specified.

     If a hook variable has a non-`nil' value, that value should be a
     list of functions.  `run-hooks' calls all the functions, one by
     one, with no arguments.

     The hook variable's value can also be a single function--either a
     lambda expression or a symbol with a function definition--which
     `run-hooks' calls.  But this usage is obsolete.

     If the hook variable is buffer-local, the buffer-local variable
     will be used instead of the global variable.  However, if the
     buffer-local variable contains the element `t', the global hook
     variable will be run as well.

 -- Function: run-hook-with-args hook &rest args
     This function runs an abnormal hook by calling all the hook
     functions in HOOK, passing each one the arguments ARGS.

 -- Function: run-hook-with-args-until-failure hook &rest args
     This function runs an abnormal hook by calling each hook function
     in turn, stopping if one of them "fails" by returning `nil'.  Each
     hook function is passed the arguments ARGS.  If this function
     stops because one of the hook functions fails, it returns `nil';
     otherwise it returns a non-`nil' value.

 -- Function: run-hook-with-args-until-success hook &rest args
     This function runs an abnormal hook by calling each hook function,
     stopping if one of them "succeeds" by returning a non-`nil' value.
     Each hook function is passed the arguments ARGS.  If this function
     stops because one of the hook functions returns a non-`nil' value,
     it returns that value; otherwise it returns `nil'.

 -- Macro: with-wrapper-hook hook args &rest body
     This macro runs the abnormal hook `hook' as a series of nested
     "wrapper functions" around the BODY forms.  The effect is similar
     to nested `around' advices (*note Around-Advice::).

     Each hook function should accept an argument list consisting of a
     function FUN, followed by the additional arguments listed in ARGS.
     The first hook function is passed a function FUN that, if it is
     called with arguments ARGS, performs BODY (i.e., the default
     operation).  The FUN passed to each successive hook function is
     constructed from all the preceding hook functions (and BODY); if
     this FUN is called with arguments ARGS, it does what the
     `with-wrapper-hook' call would if the preceding hook functions were
     the only ones in HOOK.

     Each hook function may call its FUN argument as many times as it
     wishes, including never.  In that case, such a hook function acts
     to replace the default definition altogether, and any preceding
     hook functions.  Of course, a subsequent hook function may do the
     same thing.

     Each hook function definition is used to construct the FUN passed
     to the next hook function in HOOK, if any.  The last or
     "outermost" FUN is called once to produce the overall effect.

     When might you want to use a wrapper hook?  The function
     `filter-buffer-substring' illustrates a common case.  There is a
     basic functionality, performed by BODY--in this case, to extract a
     buffer-substring.  Then any number of hook functions can act in
     sequence to modify that string, before returning the final result.
     A wrapper-hook also allows for a hook function to completely
     replace the default definition (by not calling FUN).

 -- Function: run-hook-wrapped hook wrap-function &rest args
     This function is similar to `run-hook-with-args-until-success'.
     Like that function, it runs the functions on the abnormal hook
     `hook', stopping at the first one that returns non-`nil'.  Instead
     of calling the hook functions directly, though, it actually calls
     `wrap-function' with arguments `fun' and `args'.


File: elisp,  Node: Setting Hooks,  Prev: Running Hooks,  Up: Hooks

23.1.2 Setting Hooks
--------------------

Here's an example that uses a mode hook to turn on Auto Fill mode when
in Lisp Interaction mode:

     (add-hook 'lisp-interaction-mode-hook 'auto-fill-mode)

 -- Function: add-hook hook function &optional append local
     This function is the handy way to add function FUNCTION to hook
     variable HOOK.  You can use it for abnormal hooks as well as for
     normal hooks.  FUNCTION can be any Lisp function that can accept
     the proper number of arguments for HOOK.  For example,

          (add-hook 'text-mode-hook 'my-text-hook-function)

     adds `my-text-hook-function' to the hook called `text-mode-hook'.

     If FUNCTION is already present in HOOK (comparing using `equal'),
     then `add-hook' does not add it a second time.

     If FUNCTION has a non-`nil' property `permanent-local-hook', then
     `kill-all-local-variables' (or changing major modes) won't delete
     it from the hook variable's local value.

     For a normal hook, hook functions should be designed so that the
     order in which they are executed does not matter.  Any dependence
     on the order is asking for trouble.  However, the order is
     predictable: normally, FUNCTION goes at the front of the hook
     list, so it is executed first (barring another `add-hook' call).
     If the optional argument APPEND is non-`nil', the new hook
     function goes at the end of the hook list and is executed last.

     `add-hook' can handle the cases where HOOK is void or its value is
     a single function; it sets or changes the value to a list of
     functions.

     If LOCAL is non-`nil', that says to add FUNCTION to the
     buffer-local hook list instead of to the global hook list.  This
     makes the hook buffer-local and adds `t' to the buffer-local
     value.  The latter acts as a flag to run the hook functions in the
     default value as well as in the local value.

 -- Function: remove-hook hook function &optional local
     This function removes FUNCTION from the hook variable HOOK.  It
     compares FUNCTION with elements of HOOK using `equal', so it works
     for both symbols and lambda expressions.

     If LOCAL is non-`nil', that says to remove FUNCTION from the
     buffer-local hook list instead of from the global hook list.


File: elisp,  Node: Major Modes,  Next: Minor Modes,  Prev: Hooks,  Up: Modes

23.2 Major Modes
================

Major modes specialize Emacs for editing particular kinds of text.
Each buffer has one major mode at a time.  Every major mode is
associated with a "major mode command", whose name should end in
`-mode'.  This command takes care of switching to that mode in the
current buffer, by setting various buffer-local variables such as a
local keymap.  *Note Major Mode Conventions::.

   The least specialized major mode is called "Fundamental mode", which
has no mode-specific definitions or variable settings.

 -- Command: fundamental-mode
     This is the major mode command for Fundamental mode.  Unlike other
     mode commands, it does _not_ run any mode hooks (*note Major Mode
     Conventions::), since you are not supposed to customize this mode.

   The easiest way to write a major mode is to use the macro
`define-derived-mode', which sets up the new mode as a variant of an
existing major mode.  *Note Derived Modes::.  We recommend using
`define-derived-mode' even if the new mode is not an obvious derivative
of another mode, as it automatically enforces many coding conventions
for you.  *Note Basic Major Modes::, for common modes to derive from.

   The standard GNU Emacs Lisp directory tree contains the code for
several major modes, in files such as `text-mode.el', `texinfo.el',
`lisp-mode.el', and `rmail.el'.  You can study these libraries to see
how modes are written.

 -- User Option: major-mode
     The buffer-local value of this variable holds the symbol for the
     current major mode.  Its default value holds the default major
     mode for new buffers.  The standard default value is
     `fundamental-mode'.

     If the default value is `nil', then whenever Emacs creates a new
     buffer via a command such as `C-x b' (`switch-to-buffer'), the new
     buffer is put in the major mode of the previously current buffer.
     As an exception, if the major mode of the previous buffer has a
     `mode-class' symbol property with value `special', the new buffer
     is put in Fundamental mode (*note Major Mode Conventions::).

* Menu:

* Major Mode Conventions::  Coding conventions for keymaps, etc.
* Auto Major Mode::         How Emacs chooses the major mode automatically.
* Mode Help::               Finding out how to use a mode.
* Derived Modes::           Defining a new major mode based on another major
                              mode.
* Basic Major Modes::       Modes that other modes are often derived from.
* Mode Hooks::              Hooks run at the end of major mode functions.
* Tabulated List Mode::     Parent mode for buffers containing tabulated data.
* Generic Modes::           Defining a simple major mode that supports
                              comment syntax and Font Lock mode.
* Example Major Modes::     Text mode and Lisp modes.



Local Variables:
coding: iso-8859-1
End:
